Skip to content
Advertisement

Sorting a JS array based on an array with new indices

I can’t seem to find a neat solution to this fairly simple problem. I have an array of objects likes this:

let items = [{/* */}, {/* */}, {/* */}]

Additionally, i have an array containing new array indices that i want to apply to the above items:

const newIndices = [2,0,1]

Meaning items[0]‘s new index is 2, items[1]‘s new index is 0, etc…

Right now i am using forEach, but this method requires a temporary array:

const tempItems = []
newIndices.forEach((newIndex, oldIndex) => {
  tempItems[newIndex] = items[oldIndex]
})
items = tempItems

I’m almost certain there is a neat one liner for this problem. I’ve also tried mapping, but without luck.

Advertisement

Answer

working code

let items = ['foo', 'bar', 'baz']
const newIndices = [2, 0, 1]

const result = items.map((item, index) => items[newIndices.indexOf(index)])

console.log(result)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement