如果我有一系列类型......
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数组以匹配transportFields数组的顺序。我能想到做这项工作的唯一方法是根据字符串进行过滤然后排序......
预期输出:const newTypes = ['bus','car','train'];
我试过这个:
const newTypes = transportationFields.filter((pos) => types.indexOf(pos) > -1);
但字面上看起来确切的字符串名称。如何根据transportFields顺序中是否存在类型字符串进行排序?提前谢谢你的帮助。 (使用React ES6)
答案 0 :(得分:1)
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)