数组去重
let arr = [{ name: "fct" }, { name: "fct" }, 1, 3, 4, 1, 4, 6];
// 1.Set
let newArr = Array.from(new Set(arr));
// let newArr = [...new Set(arr)]
console.log(newArr);// [{…}, {…}, 1, 3, 4, 6]
// 2.循环实现
function unique(arr) {
let len = arr.length;
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);//删除一项
len--; //长度减小
j--; // j 下标减 1
}
}
}
return arr;
}
console.log(unique(arr));
// 3.indexOf
function unique1(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(unique1(arr));
// 4. includes
function unique2(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (!newArr.includes(arr[i])) {
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(unique2(arr));
// 5. filter
function unique3(arr) {
return arr.filter((item, index) => {
return arr.indexOf(item, 0) === index
})
}
console.log(unique3(arr));