Reputation: 165
I have two arrays,
array1 = [{name: "a", id: 1},{name: "b", id: 2},{name: "c", id: 3}]
and
array2 = [1, 2] // --which are the ids
I want to return a new array (array3) to display ["a", "b"]
and if array2 = [1,3]
then array3 should be ["a", "c"]
In other words, I would like to create a new array, with the names
, corresponding to its id
.
Upvotes: 1
Views: 41
Reputation: 1100
I would go ahead and perform the below:
for(int i = 0; i<array1.length(); ++i){
for(int j = 0; j<array2.length(); ++j){
if (array1[i].id==array2[j]){
array3[j] = array[i].name;
}
}
}
Hope this is simple and it helps!
Upvotes: 1
Reputation: 18197
You can use reduce:
let a1 = [{name:'a', id:1},{name:'b', id:2},{name:'c', id:3}]
let a2 = [1,3]
let a3 = a1.reduce((carry, current) => {
if (a2.includes(current.id)) {
carry.push(current.name)
}
return carry
}, [])
alert(a3)
Upvotes: 1
Reputation: 10682
User filter
to select the elements that meet your criteria, and map
to get the property you want.
const array1 = [{name:"a", id:1},{name:"b", id:2},{name:"c", id:3}];
const array2=[1,2];
const array3 = array1.filter(i => array2.includes(i.id)).map(i => i.name);
array3
will contain ["a", "b"]
Upvotes: 1