js practical article - remove duplicate options in arrays or objects


In JavaScript, array deduplication, object deduplication, you can use a variety of methods to remove duplicates in arrays or objects. Here are some of these methods:

remove duplicates from array

Method 1: Use Set

Using a Set is the easiest and fastest way to remove duplicates from an array. A Set object is a collection of unique values ​​that can accept an array (or other object with an iterable property) as a parameter and return a new array containing unique elements. For example:

javascriptCopy code
const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]

Method 2: Use filter and indexOf

Duplicates can be removed from an array using the filter and indexOf methods. For example:

javascriptCopy code
const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArr = arr.filter((item, index) => {
  return arr.indexOf(item) === index;
});
console.log(uniqueArr); // [1, 2, 3, 4, 5]

Method 3: Using reduce and includes

Duplicates can be removed from an array using the reduce and includes methods. For example:

javascriptCopy code
const arr = [1, 2, 3, 3, 4, 5, 5];
const uniqueArr = arr.reduce((prev, cur) => {
  if (!prev.includes(cur)) {
    prev.push(cur);
  }
  return prev;
}, []);
console.log(uniqueArr); // [1, 2, 3, 4, 5]

Remove duplicates from objects

Method 1: Use for...in and hasOwnProperty

Use a for...in loop to iterate over the object's properties and use the hasOwnProperty method to check if the property is the object's own property. For example:

javascriptCopy code
const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 3,
  e: 4,
  f: 4
};
const uniqueObj = {};
for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    uniqueObj[obj[key]] = key;
  }
}
console.log(uniqueObj); // { '1': 'a', '2': 'b', '3': 'c', '4': 'e' }

Method 2: Using Object.keys and reduce

Use the Object.keys method to get all the properties of an object, then use the reduce method to remove duplicates. For example:

javascriptCopy code
const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 3,
  e: 4,
  f: 4
};
const uniqueObj = Object.keys(obj).reduce((prev, key) => {
  const value = obj[key];
  if (!prev.hasOwnProperty(value)) {
    prev[value] = key;
  }
  return prev;
}, {});
console.log(uniqueObj); // { '1': 'a', '2': 'b', '3': 'c', '4': 'e' }

Above are several ways to remove duplicates in array or object. Which method to choose depends on personal preference and specific circumstances.

Guess you like

Origin blog.csdn.net/qq_28736409/article/details/129224420