Let say I have two arrays
From here I want to filter arr1 with arr2 condition (assuming arr2 = arr1 id). I have tried this code but only return first condition.
const arr1 = [{
id: 1,
name: "Jhon"
},
{
id: 2,
name: "Barbara"
},
{
id: 3,
name: "Rio"
}
];
const arr2 = [1, 2, 5];
const filter = (arr1, arr2) => {
const output = arr1.filter(value => {
for (let i = 0; i < arr2.length; i++) {
if (value.id !== arr2[i]) {
return false;
}
return true;
}
})
console.log(output);
};
filter(arr1, arr2);
// output = [{id: 1, name: "Jhon"}]
// intended output [{id: 1, name: "Jhon"}, {id: 2, name: "Barbara}]
Anyone can tell me what I'm missing? Thank you
return true;is inside theforloop body, so it runs on the first loop iteration ifvalue.id !== arr2[i]is false. Move it after theforloop so you onlyreturn false;when none of the entries matched. Or you can usesome:.filter(value => arr2.some(v => v === value.id))