1const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]; 2// => [1, '1', 17, true, false, 'true', 'a', {}, {}]
参考答案:
1const res1 = Array.from(new Set(arr));
1const unique1 = arr => { 2 let len = arr.length; 3 for (let i = 0; i < len; i++) { 4 for (let j = i + 1; j < len; j++) { 5 if (arr[i] === arr[j]) { 6 arr.splice(j, 1); 7 // 每删除一个树,j--保证j的值经过自加后不变。同时,len--,减少循环次数提升性能 8 len--; 9 j--; 10 } 11 } 12 } 13 return arr; 14}
1const unique2 = arr => { 2 const res = []; 3 for (let i = 0; i < arr.length; i++) { 4 if (res.indexOf(arr[i]) === -1) res.push(arr[i]); 5 } 6 return res; 7}
当然也可以用include、filter,思路大同小异。
1const unique3 = arr => { 2 const res = []; 3 for (let i = 0; i < arr.length; i++) { 4 if (!res.includes(arr[i])) res.push(arr[i]); 5 } 6 return res; 7}
1const unique4 = arr => { 2 return arr.filter((item, index) => { 3 return arr.indexOf(item) === index; 4 }); 5}
1const unique5 = arr => { 2 const map = new Map(); 3 const res = []; 4 for (let i = 0; i < arr.length; i++) { 5 if (!map.has(arr[i])) { 6 map.set(arr[i], true) 7 res.push(arr[i]); 8 } 9 } 10 return res; 11}
最近更新时间:2021-07-07