How to use Set In Javascript
This method uses Set to extract unique objects by first converting each of the objects into the JSON string, then mapping it back to the objects. The output array contains the unique objects.
Syntax:
let mySet = new Set([iterable]);
Example: The below code uses a set to return an array of unique objects.
// input arr
let arr = [
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 102, title: "Arrays in JavaScript" },
{ articleId: 101, title: "Introduction to JavaScript" },
{ articleId: 103, title: "Functions in JavaScript" },
];
// Set to get unique objects
let setObj = new Set(arr.map(JSON.stringify));
let output = Array.from(setObj).map(JSON.parse);
// Output
console.log(output);
Output
[ { articleId: 101, title: 'Introduction to JavaScript' }, { articleId: 102, title: 'Arrays in JavaScript' }, { articleId: 103, title: 'Functions in JavaScript' } ]
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 through which it can be performed which are as follows:
Table of Content
- Using Set
- Using filter Method
- Using reduce Method
- Using map Method
- Using Object Key for Tracking Unique Objects
Contact Us