网站登记表,考虑了软件开发过程中的风险,海外免费云服务器,河南最新消息今天数组去重有许多种方法#xff0c;下面列举几种常见方法 数组去重数组对象去重 数组去重
使用 Set#xff1a;将数组转化为 Set 对象#xff0c;去重后再转化回数组#xff0c;Set 会自动去重
const arr [1, 2, 3, 2, 1, 4]
const newArr [...new Set(arr)]
console.log… 数组去重有许多种方法下面列举几种常见方法 数组去重数组对象去重 数组去重
使用 Set将数组转化为 Set 对象去重后再转化回数组Set 会自动去重
const arr [1, 2, 3, 2, 1, 4]
const newArr [...new Set(arr)]
console.log(newArr) // [1, 2, 3, 4]使用 filter遍历数组对每个元素判断是否在新数组中出现过。
const arr [1, 2, 3, 2, 1, 4]
const newArr arr.filter((item, index) {return arr.indexOf(item) index
})
console.log(newArr) // [1, 2, 3, 4]使用 reduce遍历数组对每个元素判断是否在新数组中出现过如果没有则将其添加到新数组中。
const arr [1, 2, 3, 2, 1, 4]
const newArr arr.reduce((acc, cur) {if (!acc.includes(cur)) {acc.push(cur)}return acc
}, [])
console.log(newArr) // [1, 2, 3, 4]使用 Map遍历数组将每个元素作为 key 存储到 Map 中去重后再转化回数组。
const arr [1, 2, 3, 2, 1, 4]
const map new Map()
arr.forEach((item) {map.set(item, true)
})
const newArr Array.from(map.keys())
console.log(newArr) // [1, 2, 3, 4]需要注意的是以上方法都无法去重包含对象、数组等引用类型的元素的数组需要使用其他方法实现。另外以上方法去重后的数组顺序可能与原数组不同如果需要保持顺序可以使用其他方法比如通过遍历原数组将不重复的元素依次添加到新数组的尾部。 数组对象去重
使用 Set Set 是 ES6 中新增的一种数据结构它类似于数组但是成员的值都是唯一的可以用来去重。我们可以使用 Set 来去重数组对象然后再将结果转换为数组。
const arr [{ id: 1, name: AAAA },{ id: 2, name: BBBB },{ id: 1, name: AAAA },{ id: 3, name: CCCC }
];const result Array.from(new Set(arr.map(JSON.stringify)), JSON.parse);
console.log(result); // [{ id: 1, name: AAAA }, { id: 2, name: BBBB }, { id: 3, name: CCCC }]使用 reduce 我们也可以使用 reduce 方法进行去重具体步骤如下 · 遍历数组中的每一个元素 · 对于每一个元素判断它是否已经出现过使用 Array.prototype.findIndex() 判断 · 如果没有出现过就将它添加到结果数组中;
const arr [{ id: 1, name: AAAA },{ id: 2, name: BBBB },{ id: 1, name: AAAA },{ id: 3, name: CCCC }
]const result arr.reduce((acc, curr) {const index acc.findIndex((item) item.id curr.id)if (index 0) {acc.push(curr)}return acc
}, [])console.log(result) // [{ id: 1, name: AAAA }, { id: 2, name: BBBB }, { id: 3, name: CCCC }]使用 Map Map 也可以用来去重数组对象具体步骤如下 · 遍历数组中的每一个元素 · 对于每一个元素判断它是否已经出现过使用 Map.has() 判断 · 如果没有出现过就将它添加到结果数组中;
const arr [{ id: 1, name: AAAA },{ id: 2, name: BBBB },{ id: 1, name: AAAA },{ id: 3, name: CCCC }
]const map new Map()
const result []for (const item of arr) {if (!map.has(item.id)) {map.set(item.id, true)result.push(item)}
}console.log(result) // [{ id: 1, name: AAAA }, { id: 2, name: BBBB }, { id: 3, name: CCCC }]