// 数组去重 { const arr = [1,2,3,4,1,23,5,2,3,5,6,7,8,undefined,null,null,undefined,true,false,true,‘中文‘,‘‘,‘‘,‘hello‘,‘中文‘]; // 第一种 const r = [...new Set(arr)]; console.log(r); // [1, 2, 3, 4, 23, 5, 6, 7, 8, undefined, null, true, false, "中文", "", "hello"] // 第二种 const R = arr.reduce((all,name) => all.includes(name) ? all :[...all,name],[]); console.log(R); // [1, 2, 3, 4, 23, 5, 6, 7, 8, undefined, null, true, false, "中文", "", "hello"] // 第三种 const k = arr.filter((item, i) => i === arr.indexOf(item)); console.log(k); // [1, 2, 3, 4, 23, 5, 6, 7, 8, undefined, null, true, false, "中文", "", "hello"] } // 统计每个元素在数组中出现的次数 { const arr = [‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘zhangsan‘, ‘lisi‘, ‘wangwu‘,‘zhaosi‘,‘liuneng‘]; const r = arr.reduce((all, name) =>{ if(name in all){ all[name]++ }else{ all[name] = 1; } return all; },{}); console.log(r); // {zhangsan: 2, lisi: 2, wangwu: 2, zhaosi: 1, liuneng: 1} } // 数组对象去重 { const arr = [ { name:‘zhangsan‘, age:12 }, { name:‘lisi‘, age:14 }, { name:‘zhangsan‘, age:12 }, { name:‘lisi‘, age:14 }, { name:‘zhangsan‘, age:12 }, { name:‘lisi‘, age:14 }, { name:‘zhangsan‘, age:12 }, { name:‘wangwu‘, age:16 }, { name:‘wagnwu‘, age:16 }, { name:‘lisi‘, age:14 }, ] // 根据 age 去重 // 方法一 const age = ‘age‘; const r = arr.reduce((all, next) => all.some((atom) => atom[age] == next[age]) ? all : [...all, next],[]); console.log(r); }
时间: 2024-11-09 00:52:19