I can’t seem to find a neat solution to this fairly simple problem. I have an array of objects likes this:
JavaScript
x
2
1
let items = [{/* */}, {/* */}, {/* */}]
2
Additionally, i have an array containing new array indices that i want to apply to the above items:
JavaScript
1
2
1
const newIndices = [2,0,1]
2
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:
JavaScript
1
6
1
const tempItems = []
2
newIndices.forEach((newIndex, oldIndex) => {
3
tempItems[newIndex] = items[oldIndex]
4
})
5
items = tempItems
6
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
JavaScript
1
6
1
let items = ['foo', 'bar', 'baz']
2
const newIndices = [2, 0, 1]
3
4
const result = items.map((item, index) => items[newIndices.indexOf(index)])
5
6
console.log(result)