Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array Filter not working (With working snippet)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading