数组对象过滤重复值

214 阅读1分钟

数据

[        {channelId: "3", children: "8", randomID: 85536},        {channelId: "3", children: "8", randomID: 89470}]

方法

function noRepeat(arr) {
    const hasObj = {}
    let newArr = []
    newArr = arr.reduce((total, next) => {
            const filterKey = next.channelId + next.children;
            hasObj[filterKey] ? "" : hasObj[filterKey] = true && total.push(next)
            return total
    }, [])
    layer.closeAll('loading')
    return newArr
}

调用

let channelData = noRepeat(channelShowList);
console.log('channelData: ', channelData);

image.png

数组对象去重

接下来介绍几种数组对象去重的方式,根据id为依据进行去重

要根据对象的 id 属性对 JavaScript 数组中的对象进行去重,可以使用多种方法。下面列出了几种常见的方法:

1. 使用 Set 对象:

    
javascript
插入代码复制代码
const array = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' },
  { id: 3, name: 'Charlie' }
];

const uniqueArray = Array.from(new Set(array.map(item => item.id))).map(id => {
  return array.find(item => item.id === id);
});

console.log(uniqueArray);

    

这种方法使用了 Set 对象来创建一个包含唯一 id 值的数组,然后使用 map 方法根据 id 查找对象并返回去重后的数组。

2. 使用 reduce 方法:

    
javascript
插入代码复制代码
const array = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' },
  { id: 3, name: 'Charlie' }
];

const uniqueArray = array.reduce((acc, curr) => {
  const isDuplicate = acc.some(item => item.id === curr.id);

  if (!isDuplicate) {
    acc.push(curr);
  }

  return acc;
}, []);

console.log(uniqueArray);

    

这种方法使用 reduce 方法遍历原始数组,并使用 some 方法检查是否已经存在具有相同 id 的对象,如果不存在则将当前对象添加到结果数组中。

3. 使用字典 (Map) 对象:

    
javascript
插入代码复制代码
const array = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' },
  { id: 3, name: 'Charlie' }
];

const uniqueArray = Array.from(new Map(array.map(item => [item.id, item]))).map(entry => entry[1]);

console.log(uniqueArray);

    

这种方法使用 Map 对象来存储键值对,其中键为 id,值为对象本身。然后通过 Array.from 方法将 Map 对象转换为数组,并使用 map 方法提取对象值,从而得到去重后的数组。