let arr = [1, 1, 2, 2, 3, 4, 3, 4, 5, 5];
一、indexOf()方法:
let newArr = []; for (let i=0; i<arr.length; i++) { if (newArr indexOf(arr[i]) === -1) { newArr.push(arr[i]); } } console.log(newArr); // [1, 2, 3, 4, 5]
二、ES6的Set:
let newArr = [...new Set(arr)]; console.log(newArr); // [1, 2, 3, 4, 5]
三、filter()函数:
let newArr = arr.filter(function (ele, index, self) { return self.indexOf(ele) === index; }) console.log(newArr); // [1, 2, 3, 4, 5]
四、ES6的includes:
let newArr = []; for (let n of arr) { if(!newArr.includes(n)) { newArr.push(n) } } console.log(newArr); // [1, 2, 3, 4, 5]
五、Array.from方法可以将Set结构转为数组:
function dedupe(array) { return Array.from(new Set(array)) } console.log(dedupe(arr)); // [1, 2, 3, 4, 5]
六、jQuery的inArray:
let newArr = []; for(let i=0; i<arr.length; i++) { if($.inArray(arr[i].newArr) == -1) { newArr.push(arr[i]) } } console.log(dedupe(arr)); // [1, 2, 3, 4, 5]