将排序数组的索引引用到旧数组(JavaScript)

时间:2018-11-27 05:42:50

标签: javascript arrays sorting

给出一些随机排列的日期字符串:

var days = ['Tues', 'Thur', 'Mon', 'Wed']

带有days[0] = 'Tues'days[1] = 'Thurs'等。排序后,我们得到

sortedDays = ['Mon', 'Tues', 'Wed', 'Thur']

但是,我想将新排序的数组的索引引用到旧数组,即旧数组的索引为(0,1,2,3),而新数组的索引为(2,0 ,3,1)。

我不知道如何实现这一目标。

3 个答案:

答案 0 :(得分:2)

在这里需要

Array.prototype.indexOf()来查找元素在数组中的位置(索引)。只需在.indexOf()数组中的每个元素上调用sortedDays

const days = ['Tues', 'Thur', 'Mon', 'Wed'];
const sortedDays = ['Mon', 'Tues', 'Wed', 'Thur'];
const sortedDaysIndices = sortedDays.map(day => days.indexOf(day));
console.log(sortedDaysIndices);

答案 1 :(得分:0)

如果要获取排序的索引,可以从[0 ... n]开始,然后根据天的排序顺序对该数组进行排序。

例如:

// Determines how we will we sort the days:
const sortDays = {
    Mon:  0,
    Tues: 1, 
    Wed:  2,
    Thur: 3,
    Fri:  4,
    Sat:  5,
    Sun:  6
}

const days = ['Tues', 'Thur', 'Mon', 'Wed', 'Thur', 'Sun', 'Mon'];
// plain indices
let index = Array.from(days, (_,i) => i)
index.sort((a, b) => sortDays[days[a]] - sortDays[days[b]])

// now indices are sorted according to days sort order
console.log("indices: ", index.join(','))

// you can use the index to sort days:
sortedDays = index.map(i => days[i])
console.log("sorted days:", sortedDays.join(','))

这样做的优点是即使原始列表中有重复项,也可以为您提供正确的索引。

答案 2 :(得分:0)

var days = ['Tues', 'Thur', 'Mon', 'Wed'];

var sortedDays = ['Mon', 'Tues', 'Wed', 'Thur'];

var indexMapping = {}
days.forEach((item, index)=> (indexMapping[item] = { 
    oldIndex: index  , newIndex: sortedDays.indexOf(item)}
 )
)

console.log(indexMapping)