简单数组去重
简单数组:由基础数据类型元素组成的数组,如 [1,‘你好’,true]
方法一 : 利用Set去重
利用 Set 数据结构自动去重的特征实现
let oldList = [1, 2, 3, 3];
let newList = Array.from(new Set(oldList)); // 得到 [1, 2, 3]
类似写法如下:
function arrDistinct(arr){
const newArr = new Set(arr);
return [...newArr]
}
let list = [1,2,2,3,4,4]
console.log(arrDistinct(list))
方法二 : 嵌套循环,自己与自己对比,有重复则删掉
let arr = [1, 2, 3, 2, 2, 1, 3, 4, 2, 5];
//去除数组中重复的数字
for (let i = 0; i < arr.length; i++) {
/*获取当前元素后的所有元素*/
for (let j = i + 1; j < arr.length; j++) {
//判断两个元素的值是否相等
if (arr[i] == arr[j]) {
//如果相等则证明出现了重复的元素,则删除j对应的元素
arr.splice(j, 1);
//当删除了当前j所在的元素以后,后边的元素会自动补位
//使j自减,再比较一次j所在位置的元素
j--;
}
}
}
console.log(arr); // 结果为 [ 1, 2, 3, 4, 5 ]
方法三 : 将不重复的元素放入新数组
//思路:创建一个新数组,循环遍历,只要新数组中有老数组的值,就不用再添加了。
function arrDistinct(array) {
let newArr = [];
for (let i = 0; i < array.length; i++) {
//开闭原则
let bool = true;
//每次都要判断新数组中是否有旧数组中的值。
for (let j = 0; j < newArr.length; j++) {
if (array[i] === newArr[j]) {
bool = false;
}
}
if (bool) {
newArr[newArr.length] = array[i];
}
}
return newArr;
}
let oldList = [1, 2, 3, 4, 5, 2, 3, 4];
let newList = arrDistinct(oldList);
console.log(newList); // 结果 [ 1, 2, 3, 4, 5 ]
方法四 : 使用 reduce
let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
if(!pre.includes(cur)){
return pre.concat(cur)
}else{
return pre
}
},[])
console.log(newArr);// [1, 2, 3, 4]
方法五 : 使用 lodash 的 uniq()
_.uniq([2, 1, 2]); // => [2, 1]
对象数组去重
对象数组:由对象组成的数组
function arrDistinctByProp(arr,prop){
//只返回第一次出现的,重复出现的过滤掉
return arr.filter(function(item,index,self){
return self.findIndex(el=>el[prop]==item[prop])===index
})
}
let list = [
{
key:'1',
name:'林青霞'
},
{
key:'2',
name:'张三丰'
},
{
key:'1',
name:'段誉'
},
{
key:'1',
name:'段誉'
}
]
//通过name属性去重
console.log(arrDistinctByProp(list,'name'))
另一种可能更容易理解,写法如下:
function soloArray(array, UID) {
let newArr = [];
let UIDlist = [];
array.forEach((item) => {
if (!UIDlist.includes(item[UID])) {
UIDlist.push(item[UID]);
newArr.push(item);
}
});
return newArr;
}
let oldList = [
{
ID: 1,
name: "王小虎",
age: 10,
},
{
ID: 2,
name: "张三",
age: 20,
},
{
ID: 2,
name: "张三",
age: 20,
},
{
ID: 3,
name: "李四",
age: 30,
},
];
let newList = soloArray(oldList, "ID");
console.log(newList);