JS-检查元素是否存在于循环中

问题描述 投票:0回答:2

我尝试在数组内循环,检查element是否不为null并忽略重复项。看起来类似于

let tempArr = [];
ARRAY.forEach(element => {
  if(element['sf'] !=null){
    if(tempArr.find(test => test.descripcion != element['sf'])){
    tempArr.push({
    id: element['id'], descripcion: element['sf'] });   
  }

但是失败了,返回空数组。

有人知道如何忽略foreach循环中的重复元素?

javascript
2个回答
0
投票

您可以为此使用reducereduce


0
投票

代替每次迭代结果,您可以使用中间集来跟踪插入的内容,然后使用简单的every

const arr = [
 { id: 0, sf: 'a' },  // ok
 { id: 1, sf: null }, // <- no
 { id: 2, sf: 'b' },  // ok
 { id: 3, sf: 'c' },  // ok
 { id: 4, sf: 'c' },  // <- no
 { id: 5, sf: 'd' }   // ok
];

const result = arr.reduce((res, el) => {
  if (el.sf !== null && res.every(x => x.descripcion !== el.sf)) {
    return res.concat({ id: el.id, descripcion: el.sf });
  }
  return res;
}, []);

console.log(result);

或者,要组合使用过滤器和映射操作,可以使用Array.filter();您所追求的逻辑可以在一定程度上得到概括,例如:

const ARRAY = [
 { id: 1, sf: null },
 { id: 2, sf: 'foo' },
 { id: 3, sf: 'bar' },
 { id: 4, sf: 'foo' }
];

const result = function(data) {
  const seen = new Set()

  return data.filter(item => {
    if (item.sf === null || seen.has(item.sf)) {
      return false;
    }
    seen.add(item.sf)
    return true;
  })
}(ARRAY);

console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.