繁体   English   中英

根据另一个数组(位置和字符串)对数组排序[ES6]

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

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

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 
    ];

我想重新排序类型数组以匹配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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM