常规方法两种
let unique1 = arr => {
var res = [],
json = {};
arr.forEach(function(value, arr) {
if(!json[value]) {
res.push(value);
json[value] = 1;
}
})
return res;
}
let unique2 = arr => {
let arr1 = arr.concat();
arr1.sort();
for (var i = 1; i < arr1.length; i++ ) {
if ( arr1[i] === arr1[ i - 1 ] ) {
arr1.splice( i--, 1 );
}
return arr1;
}
使用ES5的indexOf方法两种
let unique3 = arr => {
arr.forEach(function(value) {
res.indexOf(value) < 0 ? this.push(value) : '';
}, res = [])
}
let unique4 = arr => {
let res = [];
arr.forEach(function(value) {
(res.indexOf(item) == -1) && res.push(item);
})
return res;
}
let arr = [1, 1, 2, 2];
unique3(arr);
console.log(res);
简洁优雅版
let unique5 = arr => { return arr.filter(function (value, index, array) { return index <= array.indexOf(value);}); };