javascript 数组筛选器不工作(使用工作代码段)

cetgtptt  于 2022-10-30  发布在  Java
关注(0)|答案(3)|浏览(133)

我正在尝试按numbers过滤array。基本上,应删除id为48的汽车,因为它在numbers上不存在
我错过了什么?

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

我想保留相同的结构,我只想删除id为48的汽车

bq8i3lrv

bq8i3lrv1#

可以使用嵌套的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);

forEach内的reduce

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

mitkmikd2#

您可以使用Array.reduce()来取得预期的结果。
其思想是改变过滤条件,允许保留在numbers数组中找到的汽车对象id,并消除rest。
在您的方法中,Array.forEach只是迭代,不返回任何内容,并且Array.filter不会改变实际数组。

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

wj8zmpe13#

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

请参考代码,在数组上迭代时,我们可以改变汽车数组。

相关问题