簡體   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