Article type: Personal study notes
1. Double loop traversal
let arr = [1, 5, 6, 1, 9, 9, 2, 1];
function unique(array) {
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length; j++) {
if (array[i] === array[j]) {
arr.splice(j, 1);
}
}
}
return arr;
}
console.log(unique(arr)); // [1, 5, 6, 9, 2]
Copy the code
The next way is better, and it takes less time to iterate
2. The ES6 Set
Let arr =,5,6,1,9,9,2,1 [1]; function unique(arr) { return Array.from(new Set(arr)) } console.log(unique(arr)); // [1, 5, 6, 9, 2]Copy the code
let arr = [1, 5, 6, 1, 9, 9, 9, 9, 9, 2, 1];
function unique(arr) {
return [...new Set(arr)]
}
console.log(unique(arr)); // [1, 5, 6, 9, 2]
Copy the code
3. Use indexOf ()
Let arr =,5,6,1,9,9,2,1 [1]; function unique(arr){ if(! Array.isArray(arr)){ console.log('type error'); return; } let array = []; arr.map(item => { if(array.indexOf(item) === -1){ array.push(item) } }) return array; } console.log(unique(arr)); // [1, 5, 6, 9, 2]Copy the code
4. Use sort(), and then compare adjacent elements for equality
let arr = [1, 5, 6, 1, 9, 9, 9, 9, 9, 2, 1]; function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return; } arr = arr.sort() let arrry = [arr[0]]; arr.map((item, index) => { if (index > 0 && item ! == arr[index - 1]) { arrry.push(item) } }); return arrry; } console.log(unique(arr)); // [1, 2, 5, 6, 9]Copy the code
5. Using filter() and map(), when the found subscript is not equal to the current subscript, it is proved that this element has appeared before and is excluded
filter()
let arr = [1, 5, 6, 1, 9, 9, 9, 9, 9, 2, 1]; function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return; } return arr.filter((item, index) => { return arr.indexOf(item) === index; }) } console.log(unique(arr)); // [1, 5, 6, 9, 2]Copy the code
map()
Copy the code
Seconds!
6. Use the reduce() method
let arr = [1, 5, 6, 1, 9, 9, 9, 9, 9, 2, 1]; function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return; } return arr.reduce((prev, cur, index) => prev.includes(cur) ? prev : [...prev, cur], []); } console.log(unique(arr)); // [1, 5, 6, 9, 2]Copy the code
Show!
Conclusion: In ES6, the second method is new Set(), followed by filter() and reduce().