How to use filter Method In Javascript
This method uses the filter method in JavaScript to return only the first occurrence of each unique object in the input array, using JSON.stringify for the comparison. The output array has the unique objects stored.
Syntax:
let newArray = array.filter(callback(element, index, array));
Example: The below code uses filter and indexOf methods 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' }
];
// Filter and indexOf to get unique objects
let output = arr.filter(
(obj, index, arr) =>
{
return arr.findIndex(o =>
{
return JSON.stringify(o) === JSON.stringify(obj)
}) === index
}
);
// 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