Reputation: 21
I have two arrays. One containing different objects, the other just an array of numbers.
let fofo = [
{
image: "../assets/Male/Male1.png",
itemName: "Airmax",
price: 105.99,
gender: "Male",
id: "20",
},
{
image: "../assets/Male/Male1.png",
itemName: "Airfly `99",
price: 144.99,
gender: "Male",
id: "1",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 99.95,
gender: "Male",
id: "2",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 94.95,
gender: "Male",
id: "3",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 111.95,
gender: "Male",
id: "4",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 124.95,
gender: "Male",
id: "5",
},
];
let mytester = [20,1,3]
I am trying to find objects in array "fofo" which match any item in the "mytester" array and return them into another array.
Upvotes: 0
Views: 47
Reputation: 1
It is simple, You can use below code:
function getTheItem(){
let arr = [];
fofo.map((mainItem)=>{
mytester.map((childItem)=>{
var parsedId = parseInt(mainItem.id)
if(parsedId === childItem){
//here push it to a another array.
arr.push(mainItem);
}
});
});
retun arr;
}
parseInt() to parse the mainItem.id to int from string before the if block.
Upvotes: 0
Reputation: 25408
You can easily achive this result using reduce and find
let fofo = [{
image: "../assets/Male/Male1.png",
itemName: "Airmax",
price: 105.99,
gender: "Male",
id: "20",
},
{
image: "../assets/Male/Male1.png",
itemName: "Airfly `99",
price: 144.99,
gender: "Male",
id: "1",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 99.95,
gender: "Male",
id: "2",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 94.95,
gender: "Male",
id: "3",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 111.95,
gender: "Male",
id: "4",
},
{
image: "../assets/Male/Male1.png",
itemName: "Roshe 12",
price: 124.95,
gender: "Male",
id: "5",
},
];
let mytester = [20, 1, 3];
const result = mytester.reduce((acc, curr) => {
const isExist = fofo.find((o) => o.id === curr.toString());
if (isExist) acc.push(isExist);
return acc;
}, []);
console.log(result);
Upvotes: 1
Reputation: 3920
You can achieve this using filter
and includes
var result = fofo.filter(f => mytester.includes(parseInt(f.id)));
console.log(result);
Upvotes: 3