I have a created a array object. To simplify it I have just kept two fields, id and name.
I want to filter the mainArray and return the result in the order of the [3,9,1] as seen in the filterArray array object where with the code I am using sorts this to [1,3,9].
I have scaled down the array for simplicity.
mainArray = [
{ id: 1, name: 'AC Milan' },
{ id: 2, name: 'Juventus' },
{ id: 3, name: 'AS Roma' },
{ id: 4, name: "Napoli"},
{ id: 9, name: "Inter Milan"}
];
filterArray = [
{ id: 3 },
{ id: 9 },
{ id: 1 }
];
filteredArray = mainArray.reduce((acc, item, index) => {
if(filterArray.some(filterItem => filterItem.id === item.id)) {
// console.log(index);
acc.push(item);
}
return acc;
}, []);
for(n=0; n<=filteredArray.length; n++){
document.write(filteredArray[n].id+" - "+filteredArray[n].name+"<br/>");
};
2
Answers
I always like to make an object by
id
for easy access.You can combine
map
andfind
: