wickedk
wickedk

Reputation: 21

Referencing indices of a sorted array to the old array (Javascript)

Given some randomly arranged array of day strings:

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

with days[0] = 'Tues', days[1] = 'Thurs', etc. After sorting, we get

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

However, I'd like to reference the indices of the newly-sorted array to the old array, i.e., the old array has indices (0, 1, 2, 3) while the new array has indices (2, 0, 3, 1).

I have no idea on how to achieve this.

Upvotes: 0

Views: 44

Answers (3)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

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)

Upvotes: 0

Mark
Mark

Reputation: 92440

If you want to get the sorted indexes you can start with an array from [0...n] and then sort that array based on the sort order of the days.

For example:

// 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(','))

This has the advantage of giving you the correct indices even when you have duplicates in the original list.

Upvotes: 0

Yangshun Tay
Yangshun Tay

Reputation: 53119

Array.prototype.indexOf() would be what you need here to find the position (index) of an element within an array. Simply call .indexOf() on every element in your sortedDays array.

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

Upvotes: 2

Related Questions