var array = [1, 1, "2", '1']
1.Set()
var con = new Set(array)
console.log(con); // Set(3) {1, "2", "1"}
2.indexOf()
function unique(array) {
var res = [];
for (var i = 0, len = array.length; i < len; i++) {
var current = array[i];
if (res.indexOf(current) === -1) {
res.push(current)
}
}
return res;
}
console.log(unique(array)); // (3) [1, "2", "1"]
3.filter
function uniquef(array) {
var resp = [];
var res = array.filter(function (item, index, array) {
return array.indexOf(item) === index;
})
return res;
}
console.log(uniquef(array)); // (3) [1, "2", "1"]
4.数组对象去重
let arr = [{
id: '1',
key: '1',
value: '明月'
}, {
id: '3',
key: '2',
value: '可欣'
}, {
id: '2',
key: '3',
value: '小红'
}, {
id: '1',
key: '1',
value: '小馨'
}, {
id: '1',
key: '2',
value: '小静'
}]
let map = new Map();
for (let item of arr) {
map.set(item.id, item);
}
arr = [...map.values()];
console.log(arr)
//[{id: "1", key: "2", value: "小静"}, {id: "3", key: "2", value: "可欣"}, {id: "2", key: "3", value: "小红"}]