I’m trying to filter the array by the numbers. Basically, car with id 48 should be deleted because it does not exist on numbers
What am I missing here??
const numbers = [49, 482, 49, 49, 49, 1135, 49, 1709, 1044, 1016, 30];
const array = [{
cars: [{
id: 48
}, {
id: 49
}]
}];
array.forEach(elem => elem.cars.filter(car => !numbers.includes(car.id)));
console.log(array);
I want to keep the same structure, I just want tot delete the car with id 48
>Solution :
You can use a nested forEach
const numbers = [49, 482, 49, 49, 49, 1135, 49, 1709, 1044, 1016, 30];
const array = [{
cars: [{
id: 48
}, {
id: 49
}]
}];
array.forEach(elm => {
const cars = [];
elm.cars.forEach(car => {
if(numbers.includes(car.id)) {
cars.push({id: car.id});
}
});
elm.cars = cars;
});
console.log(array);
Or a reduce within forEach
const numbers = [49, 482, 49, 49, 49, 1135, 49, 1709, 1044, 1016, 30];
const array = [{
cars: [{
id: 48
}, {
id: 49
}]
}];
array.forEach(elm => {
elm.cars = elm.cars.reduce((curr, acc) => {
if (numbers.includes(curr.id)) {
acc.push({
id: curr.id
});
}
return acc;
}, []);
});
console.log(array);