js 数组去重

2024-01-02 05:51:08

数组去重

1 Set

const arr=[...new Set([1,2,2,3])]
const arr=Array.from(new Set([1,2,2,3]))

2 Map

const arr = [1, 1, 2, 2, 3, 4, 5];
const uniqueArray = [...new Map(arr.map(item => [item, item])).values()];

3 filter

const arr = [1, 1, 2, 2, 3, 4, 5];
const uniqueArr = arr.filter((value, index, self) => {
return self.indexOf(value) === index;
});

4 reduce

const arr =  [1, 1, 2, 2, 3, 4, 5];
const uniqueArray = arr.reduce((acc, cur) => {
if (!acc.includes(cur)) {
acc.push(cur);
}
return acc;
}, []);

文章来源:https://blog.csdn.net/weixin_56624286/article/details/135330893
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。