javascript

How to Remove duplicate elements from array in JavaScript ?

There are various different methods for finding the duplicates in the array. We will discuss two ways for finding the duplicates in the array.

//Method 1
// Defining a set of the cities
  let city = [
    "surat",
    "ahmedabad",
    "rajkot",
    "mumbai",
    "surat",
    "delhi",
    "ahmedabad",
    "anand",
  ];
  
  // For removing the duplicate values
  // we are using the Set() function
  let unique_city = [new Set(city)];
  
  // Printing the unique cities
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]

//Method 2

// Defining the unique cities from the above
  // array by using forEach loop
  let unique_city = [];
  city.forEach((c) => {
    if (!unique_city.includes(c)) {
      unique_city.push(c);
    }
  });
  console.log(unique_city);

  //Output
  ["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]


//Method-3
var my_array = [5, 4, 7, 8, 9, 2, 7, 5, 4, 8, 7];
unique_array = my_array.filter((item, index, array) => array.indexOf(item) === index);
console.log("Unique Array is : " + unique_array);

//Method - 4
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const filteredArr = arr.reduce((acc, current) => {
  const x = acc.find(item => item.id === current.id);
  if (!x) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);


//Method - 5
//Here's another possibility using the Map class constructor and values method:
const arr = [
  { id: 1, name: "test1" },
  { id: 2, name: "test2" },
  { id: 2, name: "test3" },
  { id: 3, name: "test4" },
  { id: 4, name: "test5" },
  { id: 5, name: "test6" },
  { id: 5, name: "test7" },
  { id: 6, name: "test8" }
];

const uniqueObjects = [...new Map(arr.map(item => [item.id, item])).values()]


//Method-6

		function removeDuplicates() {
			// Create an array of objects
			books = [
				{ title: "C++", author: "Bjarne" },
				{ title: "Java", author: "James" },
				{ title: "Python", author: "Guido" },
				{ title: "Java", author: "James" },
			];
			// Display the list of array objects
			console.log(books);
			// Declare a new array
			let newArray = [];
			// Declare an empty object
			let uniqueObject = {};
			// Loop for the array elements
			for (let i in books) {
				// Extract the title
				objTitle = books[i]['title'];
				// Use the title as the index
				uniqueObject[objTitle] = books[i];
			}
			// Loop to push unique object into array
			for (i in uniqueObject) {
				newArray.push(uniqueObject[i]);
			}
			// Display the unique objects
			console.log(newArray);
		}


  //Method-7
  function removeDuplicates() {
          // Create an array of objects
          books = [
              { title: "C++", author: "Bjarne" },
              { title: "Java", author: "James" },
              { title: "Python", author: "Guido" },
              { title: "Java", author: "James" },
          ];
          jsonObject = books.map(JSON.stringify);
          console.log(jsonObject);
          uniqueSet = new Set(jsonObject);
          uniqueArray = Array.from(uniqueSet).map(JSON.parse);
          console.log(uniqueArray);
}

//Method- 8
const arr = [
    {place: "here",  name: "x", other: "other stuff1" },
    {place: "there", name: "x", other: "other stuff2" },
    {place: "here",  name: "y", other: "other stuff4" },
    {place: "here",  name: "z", other: "other stuff5" }
]
function getUniqueListBy(arr, key) {
    return [...new Map(arr.map(item => [item[key], item])).values()]
}

//get unique by place
const arr1 = getUniqueListBy(arr, 'place');
//get unique by name
const arr2 = getUniqueListBy(arr, 'name')
Was this helpful?