使用for循环,利用splice去重
function sole(arr) {
const newArr = [...arr];
for (let i = 0; i < newArr.length; i++) {
for (let j = newArr.length - 1; j > i; j--) {
if (newArr[i] === newArr[j]) {
newArr.splice(j, 1);
}
}
}
return newArr;
}
使用ES6的set方法去重
const sole = (arr) => {
return [...new Set(arr)];
};
使用indexOf去重
function sole(arr) {
const newArr = [];
arr.forEach((item, i) => {
let index = arr.indexOf(item, i + 1);
if (index === -1) {
newArr.push(item);
}
});
return newArr
}
使用sort()去重
function sole(arr) {
const tempArr = [...arr];
const newArr = [tempArr[0]];
tempArr.sort((a, b) => a - b);
for (let index = 1; index < tempArr.length; index++) {
if (tempArr[index] !== tempArr[index - 1]) {
newArr.push(tempArr[index]);
}
}
return newArr;
}
利用对象的属性不能相同的特点进行去重
function sole(arr) {
const newArr = [];
const obj = Object.create(null);
arr.forEach((item, i) => {
if (obj[item] === undefined) {
newArr.push(item);
obj[item] = i;
}
});
return newArr;
}
利用includes去重
function sole(arr) {
const newArr = [];
arr.forEach((element) => {
if (!newArr.includes(element)) {
newArr.push(element);
}
});
return newArr;
}
双层循环,外层循环元素,内层循环时比较值
function sole(arr) {
const newArr = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
j = ++i;
}
}
newArr.push(arr[i]);
}
return newArr;
}