0

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

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I want to keep the same structure but just delete the car object with id 48
updated answer with the structure maintained
1

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);

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.