How to use map Method In Javascript
This method uses the map method along with callback to get unique objects by associating each object with the JSON string. The output array consists of unique objects and is printed using the log() function.
Syntax:
let newArray = array.map(callback(currentValue, index, array));
Example: The below code uses the map method 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" },
];
// Map method to get unique objects
let mapObj = new Map(
arr.map((obj) => {
return [JSON.stringify(obj), obj];
})
);
let output = Array.from(mapObj.values());
// 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