JS数组
let mixedArray = [
'string', // 字符串
123, // 数字
true, // 布尔值
{ key: 'value' }, // 对象
null, // 空值
[1, 2, 3], // 嵌套数组
function() {} , // 函数
undefined,
'string', // 字符串
123, // 数字
true, // 布尔值
{ key: 'value' }, // 对象
null, // 空值
[1, 2, 3], // 嵌套数组
function() {} , // 函数
undefined,
];
使用Set去重
let arr1 =Array.from(new Set(mixedArray))
console.log(arr1);
得到结果:
[
"string",
123,
true,
{
key: "value",
},
null,
[1, 2, 3],
function () {},
undefined,
{
key: "value",
},
[1, 2, 3],
function () {},
];
可见使用Set直接去重,对于基本数据类型起作用,引用不起作用
filter和indexOf配合使用
indexOf() 方法返回数组中第一次出现给定元素的下标,如果不存在则返回 -1。
findIndex() 方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。
let arr2 = mixedArray.filter((item, index) => mixedArray.indexOf(item) === index);
console.log(arr2,'arr2')
得到结果:
[
"string",
123,
true,
{
key: "value",
},
null,
[1, 2, 3],
function () {},
undefined,
{
key: "value",
},
[1, 2, 3],
function () {},
];
对象数组去重
const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 1, name: 'John'}];
const uniqueArr = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(uniqueArr);