根据另一个数组对数组进行排序,包括位置和字符串[ES6]

Sort array based on another array, both position and string [ES6]

本文关键字:数组 位置 字符串 ES6 包括 排序 另一个      更新时间:2023-09-26

如果我有一个类型数组。。。

const types = ['train','bus','car']; 
// needs to re-ordered to represent the order belonging to transportationFields.

还有一组字段。。。

const transportationFields = [
      'bus_station', 'bus_stop', 'bus_line', 'took_bus' // bus -> 1st in the order
      'car_type', 'buyer_of_car', 'car_model', // car -> 2nd 
      'train_number', 'train_trip_num', 'train_stop', // train -> 3rd 
    ];

我想重新排序types数组,以匹配transportationFields数组的顺序。我能想到的唯一方法是根据字符串进行过滤,然后排序…

预期输出:const newTypes = ['bus','car','train'];

我试过这个:

const newTypes = transportationFields.filter((pos) => types.indexOf(pos) > -1); 

但从字面上看,这与字符串名称完全相同。如何根据transportationFields顺序中是否存在类型字符串进行排序?提前感谢您的帮助。(使用React ES6)

const transportationFields = [
  'bus_station', 'bus_stop', 'bus_line', 'took_bus', // bus -> 1st in the order
  'car_type', 'buyer_of_car', 'car_model', // car -> 2nd 
  'train_number', 'train_trip_num', 'train_stop', // train -> 3rd 
];
const types = ['train', 'bus', 'car'];
function findIndex(a) {
  return transportationFields.findIndex(function(v) { // returns index where condition is true
    return v.includes(a) // condition is true if the value includes the string given
  })
}
types.sort(function(a, b) {
  return findIndex(a) > findIndex(b)
})
console.log(types)