Skip to content
geeksforgeeks
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Next article icon

How to Convert Array of Objects into Unique Array of Objects in JavaScript ?

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 a unique array of objects which are as follows:

Table of Content

  • Using Set
  • Using filter() and indexOf() methods
  • Using Map
  • Using reduce()
  • Using Lodash Library
  • Using some() Method
  • Using ES6 Find Method
  • Using reduce() with Set

Using Set

This approach uses the Set data structure in JavaScript, which automatically removes duplicate values. By mapping the array of objects to their JSON representations, the Set eliminates duplicate string representations, and then the unique objects are reconstructed.

Syntax:

let mySet = new Set();

Example: Using Set to create a unique array of objects by stringifying and parsing their JSON representations, eliminating duplicates based on content.

JavaScript
let arr = [
    { id: 1, name: "Geek1" },
    { id: 2, name: "Geek2" },
    { id: 1, name: "Geek1" },
    { id: 3, name: "Geek3" },
];

// unique objects using Set
let uniqueArr =
    [...new Set(arr.map(JSON.stringify))].map(JSON.parse);

// printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);

Output
Input Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
  { id: 1, name: 'Geek1' },
  { id: 3, name: 'Geek3' }
]
Unique Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
...

Using filter() and indexOf() methods

The approach uses filter() and indexOf() to create a unique array by checking the index of each object's first occurrence based on JSON string representation for precise comparison. This ensures the removal of duplicate objects from the original array.

Syntax:

let arr = inputArray.filter((value, index, self) => {
return self.indexOf(value) === index;
});

Example: Filtering out duplicate objects from the input array using filter() and indexOf() based on JSON string comparison, resulting in a unique array.

JavaScript
let arr = [
    { id: 1, name: "Geek1" },
    { id: 2, name: "Geek2" },
    { id: 1, name: "Geek1" },
    { id: 3, name: "Geek3" },
];

// Unique array using filter and indexOf functions
let uniqueArr = arr.filter(
    (value, index, self) =>
        self.findIndex((obj) =>
            JSON.stringify(obj) === JSON.stringify(value)) ===
        index
);

// Printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);

Output
Input Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
  { id: 1, name: 'Geek1' },
  { id: 3, name: 'Geek3' }
]
Unique Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
...

Using Map

This approach uses a Map to efficiently remove duplicate objects from an array. It iterates through the input array, converts each object to a string using JSON.stringify as the key, and checks if the Map already has that key. If not, it adds the key to the Map and pushes the corresponding object to the unique array. This method ensures that unique objects are retained in the final array.

Syntax:

let newArray = originalArray.map((currentValue, index, array) => {
// code
});

Example: Removing duplicate objects from the input array using a Map to track unique object keys based on their JSON string representation, resulting in a unique array.

JavaScript
let arr = [
    { id: 1, name: "Geek1" },
    { id: 2, name: "Geek2" },
    { id: 1, name: "Geek1" },
    { id: 3, name: "Geek3" },
];
let map = new Map();

// Removing duplicate objects using map
let uniqueArr = [];
arr.forEach((obj) => {
    const key = JSON.stringify(obj);
    if (!map.has(key)) {
        map.set(key, true);
        uniqueArr.push(obj);
    }
});

// Printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);

Output
Input Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
  { id: 1, name: 'Geek1' },
  { id: 3, name: 'Geek3' }
]
Unique Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
...

Using reduce()

The below approach uses the reduce() method to create a unique array of objects by comparing each object's string representation. The accumulator (acc) is updated only if the current object is not already present in the accumulator, effectively removing duplicates based on their stringified form.

Syntax:

let result = array.reduce((accumulator, currentValue, index, array) => {
//code
}, initialValue);

Example: Using the reduce method, this approach iterates through the input array, checking for duplicate objects based on their stringified representations.

JavaScript
let arr = [
    { id: 1, name: "Geek1" },
    { id: 2, name: "Geek2" },
    { id: 1, name: "Geek1" },
    { id: 3, name: "Geek3" },
];

// Removing objects using reduce()
let uniqueArr = arr.reduce((acc, obj) => {
    const existingObj = acc.find(
        (item) => JSON.stringify(item)
            === JSON.stringify(obj)
    );
    if (!existingObj) {
        acc.push(obj);
    }
    return acc;
}, []);

// Printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);

Output
Input Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
  { id: 1, name: 'Geek1' },
  { id: 3, name: 'Geek3' }
]
Unique Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
...

Using Lodash Library

Using the Lodash library's uniqWith function with a custom comparison function compares objects for uniqueness. It returns an array of unique objects by comparing their properties or values, allowing for flexible and efficient handling of object uniqueness.

Example: In this example we use Lodash's _.uniqWith and _.isEqual to remove duplicate objects from the array.

JavaScript
const _ = require('lodash');

let arr = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 1, name: 'Alice' }
];

let uniqueObjects = _.uniqWith(arr, _.isEqual);
console.log(uniqueObjects);

Output

[
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]

Using some() Method

This approach uses the some() method to create a unique array of objects. The some() method checks if at least one element in the array passes the test implemented by the provided function. If an object with the same key already exists in the unique array, it is not added again.

Syntax:

array.some(callback(element[, index[, array]])[, thisArg])

Example: The below example uses the some() method to remove duplicate objects from an array based on a specific key in JavaScript.

JavaScript
let arr = [
    { id: 1, name: "Geek1" },
    { id: 2, name: "Geek2" },
    { id: 1, name: "Geek1" },
    { id: 3, name: "Geek3" },
];

// Using some() to ensure unique objects
let uniqueArr = [];
arr.forEach(obj => {
    if (!uniqueArr.some(item => item.id === obj.id && item.name === obj.name)) {
        uniqueArr.push(obj);
    }
});

console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);

Output
Input Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
  { id: 1, name: 'Geek1' },
  { id: 3, name: 'Geek3' }
]
Unique Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
...

Using ES6 Find Method

This approach uses the ES6 find method to create a unique array of objects. The find method returns the first element in the array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

Syntax:

array.find(callback(element[, index[, array]])[, thisArg])

Example: The following example uses the find method to remove duplicate objects from an array by checking if an object with the same properties already exists in the unique array.

JavaScript
let arr = [
    { id: 1, name: "Geek1" },
    { id: 2, name: "Geek2" },
    { id: 1, name: "Geek1" },
    { id: 3, name: "Geek3" },
];

// Using find() to ensure unique objects
let uniqueArr = [];
arr.forEach(obj => {
    if (!uniqueArr.find(item => item.id === obj.id && item.name === obj.name)) {
        uniqueArr.push(obj);
    }
});

console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);

Output
Input Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
  { id: 1, name: 'Geek1' },
  { id: 3, name: 'Geek3' }
]
Unique Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
...

Using reduce() with Set

This approach uses the reduce method along with a Set to track seen object IDs. It ensures that only unique objects (based on a specified key) are added to the result array.

Example: Using reduce and Set to remove duplicate objects based on a specific key (e.g., id).

JavaScript
let arr = [
    { id: 1, name: "Geek1" },
    { id: 2, name: "Geek2" },
    { id: 1, name: "Geek1" },
    { id: 3, name: "Geek3" },
];

// Using reduce and Set to ensure unique objects based on id
let uniqueArr = arr.reduce((acc, obj) => {
    if (!acc.set) acc.set = new Set();
    
    // Check if the id has already been seen
    if (!acc.set.has(obj.id)) {
        acc.set.add(obj.id);
        acc.result.push(obj);
    }
    
    return acc;
}, { set: null, result: [] }).result;

console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);

Output
Input Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
  { id: 1, name: 'Geek1' },
  { id: 3, name: 'Geek3' }
]
Unique Array: [
  { id: 1, name: 'Geek1' },
  { id: 2, name: 'Geek2' },
...



Next Article
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?

G

gauravggeeksforgeeks
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • javascript-object

Similar Reads

    How to Convert an Object into Array of Objects in JavaScript?
    Here are the different methods to convert an object into an array of objects in JavaScript1. Using Object.values() methodObject.values() method extracts the property values of an object and returns them as an array, converting the original object into an array of objects.JavaScriptconst a = { java:
    3 min read
    How to Convert Array into Array of Objects using map() & reduce() in JavaScript?
    An array of objects can contain multiple objects with the same properties i.e. key-value pairs. But a map does not contain duplicate values which means if you convert an array of objects with duplicate objects into a map, it will contain only the unique key-value pairs. Below are the approaches to c
    2 min read
    How to convert a map to array of objects in JavaScript?
    A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
    6 min read
    How to Convert an Array of Objects to Map in JavaScript?
    Here are the different methods to convert an array of objects into a Map in JavaScript1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly.JavaScriptcon
    3 min read
    How to Convert an Array of Objects into Object in TypeScript ?
    Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript.We are given an array of objects a
    3 min read
    How to Convert Object to Array in JavaScript?
    In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
    4 min read
    How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
    Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object. Below approaches can be used to accomplish th
    3 min read
    How to convert arguments object into an array in JavaScript ?
    The arguments object is an array-like object that represents the arguments passed in when invoking a function. This array-like object does not have the array prototype chain, hence it cannot use any of the array methods. This object can be converted into a proper array using two approaches: Method 1
    5 min read
    How to Return an Array of Unique Objects in JavaScript ?
    Returning an array of unique objects consists of creating a new array that contains unique elements from an original array. We have been given an array of objects, our task is to extract or return an array that consists of unique objects using JavaScript approaches. There are various approaches thro
    5 min read
    How to Convert String of Objects to Array in JavaScript ?
    This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
    3 min read
top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences