There are many ways to de-duplicate an array. Here are some of the simplest ways
1. Use THE ES6 Set non-repetitive interface
function unique(arr) {
return Array.from(new Set(arr));
}
Copy the code
2. Using the indexOf
function unique(arr) {
let result = []
for(let index = 0; index < arr.length; index++) {
let item = arr[index]
result.indexOf(item) === -1 && (result.push(item))
}
return result;
}
Copy the code
3. Double-layer traversal
function unique(arr) {
for(let i = 0; i < arr.length-1; i++) {
for(let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1) j--
}
}
}
}
Copy the code