数组去重常用方法
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]
本文来自博客园,作者:红石榴21,转载请注明原文链接:https://www.cnblogs.com/liushihong21/p/11274727.html