数组去重常用方法

1 var arr = [1, 2, 3, 3];
2 var newArr = [], obj = {}, tmp = [];

方法一

const i = [...new Set(arr)];
console.log("方法一");
console.log(arr); // [1, 2, 3, 3]
console.log(i); // [1, 2, 3]

方法二

const j = Array.from(new Set(arr));
console.log("法二");
console.log(arr); // [1, 2, 3, 3]
console.log(j); // [1, 2, 3]

方法三

arr.forEach((item, index) => {
if (newArr.indexOf(item) < 0) {
newArr.push(item);
}
});
console.log("方法三");
console.log(arr); // [1, 2, 3, 3]
console.log(newArr); // [1, 2, 3]

方法四

for (let i = 0; i < arr.length; i++) {
if (!obj[arr[i]]) {
obj[arr[i]] = 1;
tmp.push(arr[i]);
}
}
console.log("方法四");
console.log(arr); // [1, 2, 3, 3]
console.log(tmp); // [1, 2, 3]

方法五

var arr2 = arr.filter((element, index, self) => {
return self.indexOf(element) === index;
});
console.log("方法五");
console.log(arr); // [1, 2, 3, 3]
console.log(arr2) // [1, 2, 3]
posted @ 2019-07-31 10:41  红石榴21  阅读(106)  评论(0编辑  收藏  举报