DEV Community

阳同尘
阳同尘

Posted on

JS array's unique

How to remove duplication item from JS array?
Here is 18 methods.
https://github.com/microwind/algorithms/tree/master/unique

// the multi method for array unique
// JavaScript数组去重的N种方法
(function () {
// 1. new array
console.time('time')
var arr = ['a', 'a', 1, 1, 2, 2, 'b', 'b', 2, 1]
var newArr = []
for (var i = 0, l = arr.length; i < l; i++) {
for (var j = 0; j <= i; j++) {
if (arr[i] === arr[j]) {
if (i === j) {
newArr.push(arr[i])
}
break
}
}
}
console.log('new array result:', newArr)
console.timeEnd('time')
})();

(function () {
// 1.1 new array + indexOf
console.time('time')
var arr = ['a', 'a', 1, 1, 2, 2, 'b', 'b', 2, 1]
var newArr = []
for (var i = 0, l = arr.length; i < l; i++) {
if (newArr.indexOf(arr[i]) < 0) {
newArr.push(arr[i])
}
}
console.log('new array + indexOf:', newArr)
console.timeEnd('time')
})();

(function () {
// 1.2 new array + includes
console.time('time')
var arr = ['a', 'a', 1, 1, 2, 2, 'b', 'b', 2, 1]
var newArr = []
for (var i = 0, l = arr.length; i < l; i++) {
if (!newArr.includes(arr[i])) {
newArr.push(arr[i])
}
}
console.log('new array + includes:', newArr)
console.timeEnd('time')
})();

more see: https://github.com/microwind/algorithms/tree/master/unique

Latest comments (0)