[Interview Question] 14 JS deduplication methods, see how much you know (including deduplication of array objects)

 Front-end interview question bank ( essential for interviews) Recommended: ★★★★★            

Address: Front-end interview question bank

My cousin made her own five-star red flag National Day avatar with just one click. It’s super nice.

Preface

JavaScript array is a special object used to store multiple values ​​in a continuous memory space. It is precisely because of this that we store a large amount of data in an array, but a huge amount of data will inevitably have duplication, but we There is no need for duplicate data. At this time, the array needs to be deduplicated to ensure that each array is unique. This kind of data is what we want.

Deduplication of value type data in array

Use sort to remove duplicates

First use sort to sort the array, and then judge in a single loop

let arr = [1, 1, "2", "2", "string", "string", null, null, undefined, undefined];

arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
//这里一定要多加一个条件,否者undfined就会被完全删除
  if (arr[i] === arr[i + 1] && i + 1 < arr.length) {
    arr.splice(i, 1);
    i--;
  }
}
console.log(arr);//[ null, 1, '2', 'string', undefined ]

Use recursion to remove duplicates

This method is just for removing weight. It can be used, but it is not recommended at all.

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

//其实整体与第一种循环无异,只是利用了递归的特性
arr.sort((a, b) => a - b);
function recursion(index) {
  if (index >= 1) {
  //判断相同都会删除
    if (arr[index] === arr[index - 1]) {
      arr.splice(index, 1);
    }
    //并且走递归
    recursion(index - 1);
  }
}
recursion(arr.length - 1);

console.log(arr);//[ null, 1, '2', 'string', undefined ]

Use filter to remove duplicates

As we all know, filters will return when the conditions are met. This is mainly achieved by using the feature of indexOf returning the index value.

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

//整体感觉还挺简单,就是indexOf会返回所符合条件的第一个值索引值,然后就会跳出循环
//所以每个数只能有一次与filter的index相同
arr = arr.filter((item, index) => {
  return arr.indexOf(item) === index;
});
console.log(arr);//[ 1, '2', 'string', null, undefined ]

Use object properties to remove duplicates

We all know that an object has and can only have one attribute. We can use this feature to deduplicate the values ​​in the array.

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

const obj = {};
const newArr = [];
arr.forEach((item) => {
//对象的值没有赋值之前默认undfined,所以为假,会走进判断
//当再次遇到这个属性的时候已经有值了,并且为真,则会跳过
  if (!obj[item]) {
    obj[item] = true;
    newArr.push(item);
  }
});

console.log(newArr);//[ 1, '2', 'string', null, undefined ]

Use reduce and includes to remove duplicates

The reduce method is combined with includes, which can easily and quickly remove duplicates (the reduce method here can be used)

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

arr = arr.reduce((prev, cur) => {
//当prev种不存在当前循环遍历的值,就会执行push操作,如果存在,那就存在呗,没事了
  prev.includes(cur) || prev.push(cur);
  return prev;
}, []);

console.log(arr);//[ 1, '2', 'string', null, undefined ]

Use reduce and indexOf to remove duplicates

This method is almost similar to matching indexOf. When indexOf cannot be found, -1 will be returned.

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

arr = arr.reduce((prev, cur) => {
//这里当为真了,就会执行后面的push,上面那种就是当为假了 就会执行后面push
  prev.indexOf(cur) === -1 && prev.push(cur);
  return prev;
}, []);

console.log(arr);//[ 1, '2', 'string', null, undefined ]

Double loop deduplication

Use two for loops to compare to achieve the effect of deduplication.

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

for (let i = 0; i < arr.length; i++) {
  for (let j = i + 1; j < arr.length; j++) {
  //利用两层循环,对比是否有相同的值
    if (arr[i] === arr[j]) {
      arr.splice(j, 1);
      //删除值后-1,否者会跳过一个元素
      j--;
    }
  }
}

console.log(arr);//[ 1, '2', 'string', null, undefined ]

Use indexof to remove duplicates

This is to use the feature of indexOf to remove duplicates. When it is -1, new elements will be filled in.

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

const newArr = [];
for (let i = 0; i < arr.length; i++) {
  if (newArr.indexOf(arr[i]) === -1) {
  //找不到就添加,找到了就证明已经有了,就略过
    newArr.push(arr[i]);
  }
}

console.log(newArr);//[ 1, '2', 'string', null, undefined ]

Use Set to remove duplicates

Set objects allow you to store unique values ​​of any type (whether primitive values ​​or object references).

let arr = [1, "2", 1, "2", "string", null, "string", null, undefined, undefined];

//所以就可以利用扩展运算符和new Set 来进行去重
arr = [...new Set(arr)];

console.log(newArr);//[ 1, '2', 'string', null, undefined ]

Array object deduplication

In development, we rarely encounter value type arrays that need to be deduplicated. Generally, they are in the form of array package objects. But when there are duplicate objects in the array, how to deduplicate them? After all, as an object of reference type, each one is unique.

Use the characteristics of objects to deduplicate array objects

Use loops to take advantage of the characteristics of objects for deduplication

const arr = [
  { id: 1, name: "张三", age: 18 },
  { id: 2, name: "李四", age: 13 },
  { id: 3, name: "张三", age: 15 },
  { id: 2, name: "王五", age: 16 },
  { id: 4, name: "赵六", age: 18 },
];

const obj = {};
const newArr = [];
arr.forEach((item) => {
//循环遍历,判断对象属性是否为真,为假就将数据添加到新数组中
  obj[item.id] ? "" : (obj[item.id] = true && newArr.push(item));
});
console.log(newArr);
//[
//  { id: 1, name: '张三', age: 18 },
//  { id: 2, name: '李四', age: 13 },
//  { id: 3, name: '张三', age: 15 },
//  { id: 4, name: '赵六', age: 18 }
//]

Use findIndex to deduplicate array objects

The array has a findIndex method, which will loop through it. If return is true, it will return the current index. If it cannot find it, it will return -1.

const arr = [
  { id: 1, name: "张三", age: 18 },
  { id: 2, name: "李四", age: 13 },
  { id: 3, name: "张三", age: 15 },
  { id: 2, name: "王五", age: 16 },
  { id: 4, name: "赵六", age: 18 },
];

const newArr = [];
arr.forEach((item) => {
  if (newArr.findIndex((item1) => item1.id === item.id) === -1) {
    newArr.push(item);
  }
});
console.log(newArr);
//[
//  { id: 1, name: '张三', age: 18 },
//  { id: 2, name: '李四', age: 13 },
//  { id: 3, name: '张三', age: 15 },
//  { id: 4, name: '赵六', age: 18 }
//]

Use reduce to deduplicate array objects

reduce()  The method executes a provided  reducer  function sequentially on each element in the array. Each time  the reducer is run  , the calculation results of the previous elements are passed in as parameters, and finally the results are summarized into a single return value.

const arr = [
  { id: 1, name: "张三", age: 18 },
  { id: 2, name: "李四", age: 13 },
  { id: 3, name: "张三", age: 15 },
  { id: 2, name: "王五", age: 16 },
  { id: 4, name: "赵六", age: 18 },
];

const obj = {};
//跟单遍历循环去重差不多,只是少定义了一个新的数组,主要还是对数组方法的使用
const newArr = arr.reduce((pre, cur) => {
  obj[cur.id] ? "" : (obj[cur.id] = true && pre.push(cur));
  return pre;
}, []);
console.log(newArr);
//[
//  { id: 1, name: '张三', age: 18 },
//  { id: 2, name: '李四', age: 13 },
//  { id: 3, name: '张三', age: 15 },
//  { id: 4, name: '赵六', age: 18 }
//]

Double loop to deduplicate array objects

Double cycle deduplication is similar to value type deduplication. Their IDs are compared with each other to achieve the effect of deduplication.

const arr = [
  { id: 1, name: "张三", age: 18 },
  { id: 2, name: "李四", age: 13 },
  { id: 3, name: "张三", age: 15 },
  { id: 2, name: "王五", age: 16 },
  { id: 4, name: "赵六", age: 18 },
];

for (let i = 0; i < arr.length; i++) {
  for (let j = i + 1; j < arr.length; j++) {
    if (arr[i].id === arr[j].id) {
      arr.splice(j, 1);
      j--;
    }
  }
}
console.log(arr);
//[
//  { id: 1, name: '张三', age: 18 },
//  { id: 2, name: '李四', age: 13 },
//  { id: 3, name: '张三', age: 15 },
//  { id: 4, name: '赵六', age: 18 }
//]

Use recursion to deduplicate array objects

Recursive deduplication is similar to value type deduplication, and the operation method is similar. Of course, it is not recommended.

const arr = [
  { id: 1, name: "张三", age: 18 },
  { id: 2, name: "李四", age: 13 },
  { id: 3, name: "张三", age: 15 },
  { id: 2, name: "王五", age: 16 },
  { id: 4, name: "赵六", age: 18 },
];

const obj = {};
const newArr = [];
function recursion(v) {
  if (v >= 0) {
    if (!obj[arr[v].id]) {
      obj[arr[v].id] = true;
      newArr.push(arr[v]);
    }
    recursion(v - 1);
  }
}
recursion(arr.length - 1);
console.log(newArr);
//[
//  { id: 4, name: '赵六', age: 18 },
//  { id: 2, name: '王五', age: 16 },
//  { id: 3, name: '张三', age: 15 },
//  { id: 1, name: '张三', age: 18 }
//]

end

Array deduplication is an essential operation in production. When a large amount of data is obtained, there must be duplicate data. If the back-end processing is not good, it can only be processed by the front-end. Although there are many methods, although as mentioned above There are 14 methods of deduplication, but some methods are similar. The best one suits you. As long as you know one method of deduplication, you can solve 99% of the scene needs.

 Front-end interview question bank ( essential for interviews) Recommended: ★★★★★            

Address: Front-end interview question bank

 My cousin made her own five-star red flag National Day avatar with just one click. It’s super nice.

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/133277252