简体   繁体   English

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

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

If I have an array of types... 如果我有一个类型数组...

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

And an array of fields... 还有一系列字段...

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

I'd like to re-order the types array to match the order of the transportationFields array. 我想重新排序类型数组以匹配TransportationFields数组的顺序。 The only way I can think of making this work would be to filter based on string and then sort... 我能想到的唯一方法是根据字符串进行过滤,然后进行排序...

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

I've tried this: 我已经试过了:

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

But that literally looks to the exact string name. 但这从字面上看是确切的字符串名称。 How can I sort based on if the string of the types is present in the transportationFields order? 如何根据TransportationFields订单中是否存在类型的字符串进行排序? Thank you for your help in advance. 提前谢谢你的帮助。 (Using React ES6) (使用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