Open In App

How to remove duplicates from an array of objects using JavaScript ?

Last Updated : 06 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This article focuses on removing duplicate object elements from an array. We’re provided with an array of objects, and our goal is to eliminate duplicate objects from the list.

duplicates

These are the methods to solve this problem which are discussed below:

Method 1: Using one of the keys as an index

  • A temporary array is created that stores the objects of the original array using one of its keys as the index.
  • Any of the object properties can be used as a key. The key is extracted from the object and used as the index of the new temporary array.
  • The object is then assigned to this index.
  • This approach will remove the duplicate objects as only one of each object of the original array will get assigned to the same index. 

Example: This example is the implementation of the above-explained method.

Javascript
function removeDuplicates() {

    // Create an array of objects
    books = [
        { title: "C++", author: "Bjarne" },
        { title: "Java", author: "James" },
        { title: "Python", author: "Guido" },
        { title: "Java", author: "James" },
    ];

    // 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);
}
removeDuplicates();

Output
[
  { title: 'C++', author: 'Bjarne' },
  { title: 'Java', author: 'James' },
  { title: 'Python', author: 'Guido' }
]

Method 2: Converting the array to a Set to remove the duplicates

  • A Set object holds only unique values of any type. This property can be used to store only the objects that are unique in the array.
  • Each object of the array is first converted into a JSON-encoded string using the JSON.stringify method.
  • The JSON-encoded string is then mapped to an array using the map() method. A new set is created by passing this array to the new set constructor.
  • This step will remove all the duplicate elements as the JSON-encoded strings will be the same for the same elements.
  • The set is then converted to an Array using the from() method, passing the set as a parameter. This array will not have duplicated objects. 

Example: In this example, we will remove the duplicate values from an array of objects by converting the array to a set to remove the duplicates.

Javascript
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);
    uniqueSet = new Set(jsonObject);
    uniqueArray = Array.from(uniqueSet).map(JSON.parse);

    console.log(uniqueArray);
}
removeDuplicates();

Output
[
  { title: 'C++', author: 'Bjarne' },
  { title: 'Java', author: 'James' },
  { title: 'Python', author: 'Guido' }
]

Method 3: Using filter() and includes() Method

In this method, we will filter the data from the book and include the data which is not repeated in a new array.

Example: This example is the implementation of the above-explained method.

Javascript
const books = [
    { title: "C++", author: "Bjarne" },
    { title: "Java", author: "James" },
    { title: "Python", author: "Guido" },
    { title: "Java", author: "James" },
];

const ids = books.map(({ title }) => title);
const filtered = books.filter(({ title }, index) =>
    !ids.includes(title, index + 1));

console.log(filtered);

Output
[
  { title: 'C++', author: 'Bjarne' },
  { title: 'Python', author: 'Guido' },
  { title: 'Java', author: 'James' }
]

Method 4: Using filter() and findIndex() Method

In this method, we will filter() the array by using the Array.findIndex() method to return the first index of the element in a given array that satisfies the provided testing function (passed in by the user while calling)

Example: This example is the implementation of the above-explained method.

Javascript
const books = [
    { title: "C++", author: "Bjarne" },
    { title: "Java", author: "James" },
    { title: "Python", author: "Guido" },
    { title: "Java", author: "James" },
];

const unique = books.filter((obj, index) => {
    return index === books.findIndex(o => obj.title === o.title);
});

console.log(unique);

Output
[
  { title: 'C++', author: 'Bjarne' },
  { title: 'Java', author: 'James' },
  { title: 'Python', author: 'Guido' }
]

Method 5: Using Lodash _.uniq() method

In this method, we are using _.uniq() method which returns the unique value present in the given array.

Example: This example is the implementation of the above-explained method.

Javascript
// Requiring the lodash library 
const _ = require("lodash");

// Use of _.uniq() 
// method
let arr = _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');

// Printing the output 
console.log(arr);

Output:

 [{ 'x': 1 }, { 'x': 2 }]


Previous Article
Next Article

Similar Reads

How to Remove Duplicates from an Array of Objects using TypeScript ?
We are given an array of objects and we have to check if there are duplicate objects present in the array and remove the duplicate occurrences from it. Otherwise, return the array as it is. Examples of Removing Duplicates from an Array of Objects using TypeScript Table of Content Using filter() and findIndex() methodsUsing Set and Array.from() meth
4 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
5 min read
How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
4 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
5 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing filter and includes MethodsIn this approach, we a
2 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to update an array of objects with another array of objects in the Lodash library: Table of Content Using _.merge function from lodashUsing _.mergeWith function
2 min read
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
4 min read
How to remove object from array of objects using JavaScript ?
Given a JavaScript array containing objects, the task is to delete certain objects from an array of objects. and return the newly formed array after deleting that element. There are two approaches to solving this problem which are discussed below: Table of Content Using array.forEach() methodUsing array.map() methodApproach 1: Using array.forEach()
1 min read
How to Remove Duplicates in JSON Array JavaScript ?
In JavaScript, removing duplicates from a JSON array is important for data consistency and efficient processing. We will explore three different approaches to remove duplicates in JSON array JavaScript. Use the methods below to remove Duplicates in JSON Array JavaScript. Table of Content Using SetUsing forEach LoopUsing filter MethodUsing SetIn thi
3 min read
How to get all unique values (remove duplicates) in a JavaScript array?
We are going to learn How to get all unique values (remove duplicates) in a JavaScript array. Given an array with various values, our objective is to filter out any duplicates and display the resulting array in the console. [caption width="800"]get all unique values (remove duplicates) in a JavaScript array[/caption]We can get all unique values in
5 min read