I have an array of objects, and another array of indexes. I need to get a new array that includes just the elements of the first array that have indexes that match the indexes that are the elements of the second array. In other words, consider this first array of objects:
const arr1 = [{id: 'abc'}, {id: 'def'}, {id: 'ghi'}];
And a second array of indexes:
const arr2 = [0, 1];
Then my final array should be this:
const finalArr = [{id: 'abc'}, {id: 'def'}];
The options I’ve considered seem unnecessarily longwinded. What is a terse way I can get the finalArr
from the first two as I’ve described above?
You can map the second array:
Using
forEach()
, iterate over thearr2
, get the object from thearr2
corresponding to the current item ofarr1
and push it in another array that will represent your final result.