js 数组去重
封装了几个js对数组的处理
1.获取数组中某一列的全部内容
let arr = [ { id:'232122', name: '张三' },{ id:'12122', name:'王二', function array_column(arr, column) { return arr.map(x => x[column]) } array_column(arr,'name'); // ['张三','王二']
2.数组去重
let arr = [1,1,1,2,3]; function array_unique(arr) { return [...new Set(arr)]; } array_unique(arr); //[1,2,3]
3.二维数组去重
let matrix=[ [1,2,3,4], [3,4,5,6], [1,2,3,4] ] function array_unique_two_dimensional(arr) { var obj = {}; for (var i = 0; i < arr.length; i++) { // 判断当前项是否遍历过,是则删除,否存入obj以作对照 if (obj.hasOwnProperty(arr[i])) { arr.splice(i, 1) i++; } obj[arr[i]] = i; } return arr; }; array_unique_two_dimensional(matrix); // [[3,4,5,6], [1,2,3,4]];
4.二维数组去重,指定字段
let arr = [ { id:'232122', name: '张三' },{ id:'12122', name:'王二', }, { id:'121322', name:'王二', } ]; function array_unique_two_dimensional(arr,param = ''){ const res = new Map(); return arr.filter((a) => !res.has(a[param]) && res.set(a[param], 1)) } array_unique_two_dimensional(arr,'name'); //[{ id:'232122', name: '张三' },{ id:'12122', name:'王二', }]