0

NOTE: I understand that the title is phrased ambiguously and the explanation below is simplistic, apologies I'm a little new to JS

I have this array of objects (this.listOfAnimals). I believe the purple represents the ids of each object.

enter image description here

I have a list of numbers below which are dynamically generated:

this.arrayOfNumbers = [0,1,2,3,4,5] which is set using:

while(this.firstNumber <= this.lastNumber) {
  this.arrayOfNumbers.push(this.firstNumber++);
}

enter image description here

I need to get a list of items from this.listOfAnimals with ids = the numbers in the array this.arrayOfNumbers. How can I do this?

For example, I need a list of all items in this.listOfAnimals whose ids are 0,1,2,3,4,5 (coming from the array in the 2nd image). All of the data is dynamically generated so I can't use hardcoded code like this.listOfAnimals[0].

One_for_all
  • 299
  • 1
  • 13
  • 2
    The purple is just array indexes, not IDs. – Barmar Oct 20 '20 at 19:49
  • Does this answer your question? [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Randy Casburn Oct 20 '20 at 19:49
  • Ah in terms of the link, I'm not entirely sure but Barmar's answer below worked quite well for extracting the objects using their indexes – One_for_all Oct 20 '20 at 20:12

3 Answers3

0

try this

this.arrayOfNumbers.map(id => { console.log(this.listOfAnimals[id]); });
MD AZAD HUSSAIN
  • 202
  • 1
  • 6
0

Use map() to iterate over arrayOfNumbers, and use the values as indexes into listOfAnimals

let selectedAnimals = this.arrayOfNumbers.map(n => this.listOfAnimals[n]);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If you have lodash in your project, _.at can do the trick:

    const letters = ['a', 'b', 'c', 'd', 'e', 'f'];
    const indices = [0, 2, 4];

    const selected = _.at(letters, indices)

    console.log(selected);
    // ["a", "c", "e"]
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>