[Javascript] 4 ways to remove duplicates elements from an array with Javascript

Remove duplicates elements from an array is a common array task Javascript offers different alternatives to accomplish it. You can use a mix of methods like Array.filter and Array.indexOf or a more complex method and also more flexible as Array.reduce or just a simple Array.forEach that allows you tu iterate over the array in an imperative way. Or you can also use more complex data estructures as Set

/* IndexOf */
let dataArr = ["1", "5", "6", "1", "3", "5", "90", "334"];

let resultArr = dataArr.filter((data, index) => {
  return dataArr.indexOf(data) === index;
});
console.log(resultArr); //["1", "5", "6", "3", "90", "334"]

/** SET */
dataArr = ["1", "5", "6", "1", "3", "5", "90", "334", "90"];

//creates  Set object from array of unique element
const dataArrWithSet = new Set(dataArr);

//we can create Set object to array also using spread operator
resultArr = [...dataArrWithSet];

console.log(resultArr);

/* Reduce */
dataArr = ["1", "5", "6", "1", "3", "5", "90", "334", "90"];

resultArr = dataArr.reduce((acc, item) => {
  if (!acc.includes(item)) {
    acc.push(item);
  }
  return acc;
}, []);

console.log(resultArr); //["1", "5", "6", "3", "90", "334"]

/* Foreach */
dataArr = ["1", "5", "6", "1", "3", "5", "90", "334", "90"];

const uniqueArr = [];
dataArr.forEach(item => {
  //pushes only unique element
  if (!uniqueArr.includes(item)) {
    uniqueArr.push(item);
  }
});

console.log(uniqueArr); //["1", "5", "6", "3", "90", "334"]

/* From Objects using Map */
var arrOfObj = [
  {
    name: "abc",
    age: 27
  },
  {
    name: "pqr",
    age: 27
  },
  {
    name: "abc",
    age: 27
  }
];
dataArr = arrOfObj.map(item => {
  return [item.name, item];
}); // creates array of array
var maparr = new Map(dataArr); // create key value pair from array of array

var result = [...maparr.values()]; //converting back to array from mapobject

console.log(result); //[{"name":"abc","age":27},{"name":"pqr","age":27}]

/** Using Set */
arrOfObj = [
  {
    id: 1,
    name: "abc",
    age: 27
  },
  {
    id: 2,
    name: "pqr",
    age: 27
  },
  {
    id: 1,
    name: "abc",
    age: 27
  }
];

var setObj = new Set(); // create key value pair from array of array

result = arrOfObj.reduce((acc, item) => {
  if (!setObj.has(item.id)) {
    setObj.add(item.id, item);
    acc.push(item);
  }
  return acc;
}, []); //converting back to array from mapobject

console.log(result); //[{"id":1,"name":"abc","age":27},{"id":2,"name":"pqr","age":27}]
原文地址:https://www.cnblogs.com/Answer1215/p/13488389.html