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?

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

  1. You can map the second array:

    const arr1 = [{id: 'abc'}, {id: 'def'}, {id: 'ghi'}];
    const arr2 = [0, 1];
    
    const arr3 = arr2.map(index => arr1[index]);
    console.log(arr3);
    Reply
  2. Using forEach(), iterate over the arr2, get the object from the arr2 corresponding to the current item of arr1 and push it in another array that will represent your final result.

    const arr1 = [{id: 'abc'}, {id: 'def'}, {id: 'ghi'}];
    const arr2 = [0, 1];
    
    const result = [];
    arr2.forEach(index => result.push(arr1[index]));
    
    console.log(result);
    Reply

Leave a Comment