接上篇 数组去重 - 创造 101 种方法 (上)
- 6,map
- function demo6(ary){
- var res = [];
- ary.sort().map((current)=>{
- if(res.length == 0 || res[res.length-1] !== current){
- res.push(current)
- }
- });
- console.log(res);
- }
- demo6(arr);
结果:[0, "1", 1, 10, 2, 3, 4, 5, "6", 6, 7, 8, 9, false, "false", null, true, "大唐", "盛世", undefined]
- 7,filter
- function demo7(ary){
- var res = [];
- ary.sort().filter((current)=>{
- if(res.length == 0 || res[res.length-1] !== current){
- res.push(current)
- }
- });
- console.log(res);
- }
- demo7(arr);
结果:[0, "1", 1, 10, 2, 3, 4, 5, "6", 6, 7, 8, 9, false, "false", null, true, "大唐", "盛世", undefined]
- 8,forEach
- function demo8(ary){
- var res = [];
- ary.sort().forEach((current)=>{
- if(res.length == 0 || res[res.length-1] !== current){
- res.push(current)
- }
- });
- console.log(res);
- }
- demo8(arr);
结果:[0, "1", 1, 10, 2, 3, 4, 5, "6", 6, 7, 8, 9, false, "false", null, true, "大唐", "盛世", undefined]
不难看出, reduce,map,filter,forEach 去重的原理是一样的,
另外, 把 if 部分换成 indexOf :res.indexOf(current) === -1 && res.push(current) 结果也完全一样
9, 递归
- var i = 0,
- res =[];
- arr = arr.sort();
- function demo9(i){
- if(i>=0 && i <= arr.length){
- res.indexOf(arr[i]) === -1 && res.push(arr[i]);
- i++;
- demo9(i)
- }
- }
- demo9(i);
- console.log(res);
结果:[0, "1", 1, 10, 2, 3, 4, 5, "6", 6, 7, 8, 9, false, "false", null, true, "大唐", "盛世", undefined]
- 10,Set
- function demo10(ary){
- var res = [...new Set(ary.sort())];
- console.log(res);
- }
- demo10(arr);
结果:[0, "1", 1, 10, 2, 3, 4, 5, "6", 6, 7, 8, 9, false, "false", null, true, "大唐", "盛世", undefined]
11,Map
此 Map 非 彼 map
- function demo11 (arr) {
- const seen = new Map();
- var res = arr.filter((a) => !seen.has(a) && seen.set(a, 1));
- console.log(res);
- }
- demo11(arr.sort());
结果:[0, "1", 1, 10, 2, 3, 4, 5, "6", 6, 7, 8, 9, false, "false", null, true, "大唐", "盛世", undefined]
来源: http://www.qdfuns.com/article/25669/d13f2a88fb5da5dc02e33b3e6c6c3c0d.html