By default, I have arrays with the name of the continents.
europe= [];
northAmerica = [];
southAmerica = [];
asia = [];
And i have two arrays with some data
arr1 = [1,3];
arr2 = [
{ country: "Brazil", id: 1, continent: "southAmerica" },
{ country: "Germany", id: 2, continent: "europe" },
{ country: "India", id: 3, continent: "asia" },
{ country: "China", id: 4, continent: "asia" },
];
If the id matches in the arrays, I need to send the string obj.country to the corresponding array of the continent.
I tried like this:
arr2.map((item) => {
if (arr1.find((id) => id === item.id)) {
if (item.continent === "southAmerica") {
southAmerica.push(item.country);
}
if (item.continent === "asia") {
asia.push(item.country);
}
}
});
But only the last value is sent to the arrays.
3
Answers
You want to use an object to make accessing the arrays a lot easier. You want to use forEach and includes.
using reduce
Do it like this.