lost9123193
lost9123193

Reputation: 11030

Suggested way to Map an Object array to Array of Ids

If given an array of ids [1,2,3,4,5]

And an object array:

[{animal:tiger, id:1}, {animal:"fish", id:2}]

What would be the suggested way to return 'tiger, fish'. Would that be through using .map or would a for loop be better for constructing the sentence?

Upvotes: 0

Views: 1147

Answers (4)

Doppio
Doppio

Reputation: 2188

I suggest two options, depending on your data & use cases.

1. map + find if the animal kingdoms are not too many to loop through.

const animals = [
  {animal:tiger, id:1},
  {animal:"fish", id:2}
]

const ids = [1,2,3,4,5];

const names = ids.map(id =>
  animals.find(animal => animal.id === id));

2. convert animals array to object first, for easier frequent access later. One upfront loop, then easier to access by id later.

const animals = [
  {animal: "tiger", id:1},
  {animal: "fish", id:2}
]

/*
  Convert
    [{animal:tiger, id:1}, {animal:"fish", id:2}]
  to
    {
      1: { animal: "tiger", id: 1 },
      2: { animal: "fish", id: 2 },
    } 

*/
const animalsObj = animals.reduce((acc, animal) => {
  return {
    ...acc,
    [animal.id]: animal,
  }
}, {});

const ids = [1,2,3,4,5];

const names = ids.map(id => animalsObj[id].animal)

Upvotes: -1

Artem Arkhipov
Artem Arkhipov

Reputation: 7455

What you need is just go through the list of ids and find corresponding animal in the animals list.

Note, that in case animals list is not expected to store all the animals and some of them are missing, you will need to add additional filter step to be sure that no undefined values appear on the last map step.

const ids = [1,5,2,4,3,6]; // added 6 which is missing in animals
const animals = [
  {name:'Tiger',id:1},
  {name:'Horse',id:2},
  {name:'Mouse',id:3},
  {name:'Elephant',id:4},
  {name:'Cat',id:5}
];

const result = ids
                .map(id => animals.find(a => a.id === id))
                .filter(Boolean) // this will exclude undefined
                .map(a => a.name)
                .join(',');

console.log(result);

Upvotes: 3

Chase
Chase

Reputation: 5615

I'm guessing you only want the animal names who's id appears in your array. If so, you could filter the array of objects first, followed by a map and a join.

let idarr = [1, 2, 3, 4];
let objarr = [{
  animal: "tiger",
  id: 1
}, {
  animal: "fish",
  id: 2
}];

console.log(objarr.filter(x => idarr.includes(x.id)).map(x => x.animal).join(', '))

Upvotes: -1

triihim
triihim

Reputation: 62

var ids = [1,2,3,4,5];
var objects = [{ animal:"tiger", id: 1 }, { animal: "fish", id: 2 }];

objects.map(function(o) { if(ids.includes(o.id)) return o.animal }).join();

Upvotes: 0

Related Questions