Getting a 3rd Array Based on Comparing Array of Indexes with an Array of Objects

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?

2 thoughts on “Getting a 3rd Array Based on Comparing Array of Indexes with an Array of Objects”

Leave a Comment