Tiago Silva
Tiago Silva

Reputation: 259

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

Upvotes: 0

Views: 53

Answers (3)

codeandcloud
codeandcloud

Reputation: 55200

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((acc, curr) => {
    if (numbers.includes(curr.id)) {
      acc.push({
        id: curr.id
      });
    }
    return acc;
  }, []);
});

console.log(array);

Upvotes: 1

ambianBeing
ambianBeing

Reputation: 3529

You could use Array.reduce() to acheive the expected result.

The idea is to change the filter condition which allows to keep the car objects id found in the numbers array and eliminate rest.

In your approach Array.forEach is just iteration without returning anything and Array.filter does not mutate the actual array.

const numbers = [49, 482, 49, 49, 49, 1135, 49, 1709, 1044, 1016, 30];

const array = [
  {
    cars: [
      {
        id: 48,
      },
      {
        id: 49,
      },
    ],
  },
];

const res = array.reduce((prev, curr) => {
  prev.push({ cars: curr.cars.filter((car) => numbers.includes(car.id)) });
  return prev;
}, []);

console.info("result::", res);

Upvotes: 1

Phani
Phani

Reputation: 129

const numbers = [49, 482, 49, 49, 49, 1135, 49, 1709, 1044, 1016, 30];

const array = [
    {
        cars: [{id: 48,},{id: 49,}],
    },
];

array.forEach((elem) => {
    const elemCopy = elem;
    elemCopy.cars = elem.cars.filter((car) => numbers.includes(car.id))
});

console.log(array);

Please refer the code, while iterating over array we can mutate the cars array.

Upvotes: -1

Related Questions