根据另一个数组对数组进行排序,包括位置和字符串[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
];
我想重新排序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)
相关文章:
- 如何从某个位置顺时针和逆时针循环数组
- 将javascript数组中的项移动到特定位置的有效方法
- 生成ACF标记位置的数组(元素列表后缺少])
- 基于javascript中位置的数组差异
- Javascript删除数组中某个位置之后的项
- 在数组中迭代时的JS循环位置
- 在两个位置显示数组中的随机单词
- javascript递归,按数组位置查找子级
- 检查数组位置是否真的未定义
- 检查值存在于数组位置
- 在数组位置获取并设置cookie值
- 如何访问成员模板中的数组位置
- 递增数组位置
- 返回最低数字的数组位置(非负数)
- 我如何使一个按钮改变Javascript数组位置
- 我如何保存字符串的每个字母在不同的数组位置?并合并回单个字符串
- 下划线-比较两个对象数组(位置)
- for循环中的Ajax不会返回数组位置的正确值,尽管闭包绑定了当前值位置的范围
- 根据对象在Firebase中的数组位置检索对象
- 当使用x作为索引号时.要在函数中显示数组位置,数组返回undefined