In this article, we will explore the concept of JavaScript arrays that contain distinct objects.
Following are the methods that we can use to extract an array of unique objects:
- Utilizing Set method
- Utilizing filter and indexOfMethods
- Utilizing reduce method
- Utilizing map method
- Utilizing map, set and from methods
- Utilizing Lodash _.uniqBy method and map
Utilizing Set
The method known as 'set' is employed to retrieve distinct objects. Initially, it transforms each object into a JSON string representation and subsequently maps it back to its original object form.
Syntax:
let mySet = new Set([iterable]);
Demo 1:
We will employ the Set method to obtain an array consisting of distinct objects.
Code:
let arr = [
{ productId: 25, bookTitle: "Laptop" },
{ productId: 26, bookTitle: "Microwave Oven" },
{ productId: 25, bookTitle: "Laptop" },
{ productId: 26, bookTitle: "Microwave Oven" },
{ productId: 27, bookTitle: "Personal Computer" },
{ productId: 28, bookTitle: "Air Conditioner" },
];
let setObj = new Set(arr.map(JSON.stringify));
let output = Array.from(setObj).map(JSON.parse);
console.log(output);
Output:
The output showcases a diverse collection of distinct objects.
Demo 2:
We will employ the Set method to derive the distinct values from a collection of objects within an array.
Code:
let students_details = [
{ name: "Divyansh", age: 18 },
{ name: "Chetan", age: 19 },
{ name: "Ashu", age: 23 },
{ name: "Rohit", age: 19 },
{ name: "Shivam", age: 18 },
];
let desired_output = (students_details) => {
let unique_values = [
...new Set(students_details.map((element) => element.name)),
];
return unique_values;
};
console.log(desired_output(students_details));
Output:
In the output, we can observe distinct values derived from an array of objects.
Utilizing filter and indexOfMethods
The filter function is employed to yield solely the distinct object. We will leverage the JSON.stringify function to facilitate the comparison of the objects.
Syntax:
let new_array = array.filter(callback(element, index, array));
Demo 1:
We will employ the reduce method to obtain distinct objects.
Code:
let book_array = [
{ bookId: 501, bookTitle: 'Pride and Prejudice' },
{ bookId: 502, bookTitle: 'Lord of the Rings' },
{ bookId: 503, bookTitle: 'War and Peace' },
{ bookId: 501, bookTitle: 'Pride and Prejudice' },
{ bookId: 501, bookTitle: 'Pride and Prejudice' },
{ bookId: 504, bookTitle: 'A Town Like Alice' }
];
let outcome = book_array.filter(
(obj, index, book_array) =>
{
return book_array.findIndex(o =>
{
return JSON.stringify(o) === JSON.stringify(obj)
}) === index
}
);
console.log(outcome);
Output:
We can observe the collection of distinct objects obtained through the application of the filter method.
Demo 2:
We will employ the filter method to obtain distinct values.
Code:
let cosmetics_details = [
{ name: "liptick", price: 1500 },
{ name: "foundation", price: 2500 },
{ name: "eyeliner", price: 1000 },
{ name: "blusher", price: 500 },
{ name: "foundation", price: 5000 },
{ name: "blusher", price: 500 },
];
let desired_output = (cosmetics_details) => {
let unique_values = cosmetics_details
.map((item) => item.name)
.filter(
(value, index, current_value) => current_value.indexOf(value) === index
);
return unique_values;
};
console.log(desired_output(cosmetics_details));
Output:
We can observe the distinct values derived from a collection of objects.
Utilizing map method
The map function is employed to retrieve distinct objects from the provided array. To verify the uniqueness of these objects, we will make use of the JSON.stringify method.
Syntax:
let new_array = array.map(callback(currentValue, index, array));
Demo 1:
We will employ the map function to retrieve the distinct objects.
Code:
let series_array = [
{ seriesId: 61, title: "Family Aaj Kal" },
{ seriesId: 62, title: "Parasyte: The Grey" },
{ seriesId: 63, title: "Lootere" },
{ seriesId: 64, title: "Big Girls Don't Cry" },
{ seriesId: 63, title: "Lootere" },
{ seriesId: 61, title: "Family Aaj Kal" },
];
let mapObj = new Map(
series_array.map((obj) => {
return [JSON.stringify(obj), obj];
})
);
let outcome = Array.from(mapObj.values());
console.log(outcome);
Output:
We can observe the collection of distinct objects obtained through the use of the map function.
Demo 2:
We will employ the map function to extract the distinct value of bookTitle.
Code:
let book_array = [
{ bookId: 501, bookTitle: 'Pride and Prejudice' },
{ bookId: 502, bookTitle: 'Lord of the Rings' },
{ bookId: 503, bookTitle: 'War and Peace' },
{ bookId: 502, bookTitle: 'Pride and Prejudice' },
{ bookId: 502, bookTitle: 'Pride and Prejudice' },
{ bookId: 504, bookTitle: 'A Town Like Alice' }
];
let mapObj = new Map(
book_array.map((obj) => {
return [JSON.stringify(obj), obj];
})
);
let outcome = Array.from(mapObj.values());
console.log(outcome);
Output:
We can observe the collection of distinct values for bookTitle.
Utilizing map, set and from methods
We will employ the map, set, and from methods to generate an array containing distinct objects.
Demo:
We will obtain the distinct values of laptop brands by employing the map, set, and from methods.
Code:
let laptop_details = [
{ name: "Dell - Inspiron 15", brand: "Dell" },
{ name: "ASUS TUF Gaming F17", brand: "Asus" },
{ name: "Lenovo - ThinkPad X1", brand: "Lenovo" },
{ name: "Lenovo - Yoga Book 9i", brand: "Lenovo" },
{ name: "Dell - Vostro 16", brand: "Dell" },
];
const propertyValues =
laptop_details.map(obj => obj['brand']);
const uniqueValuesSet =
new Set(propertyValues);
const distinctValues =
Array.from(uniqueValuesSet);
console.log(distinctValues);
Output:
We can observe the diverse collection of distinct laptop brand values.
Utilizing Lodash _.uniqBy method and map
We will employ the Lodash method _.uniqBy in conjunction with map to derive an array containing unique objects.
Demo:
We will retrieve the distinct value of the state by employing the Lodash _.uniqBy method in conjunction with map.
Code:
const _ = require("lodash");
let cs = [
{ city: "Noida", state: "Uttar Pradesh" },
{ city: "Meerut", state: "Uttar Pradesh" },
{ city: "Mumbai", state: "Maharashtra" },
{ city: "Nagpur", state: "Maharashtra" },
{ city: "Kolkata", state: "West Bengal" },
{ city: "Dehradun", state: "Uttarakhand" },
];
let uniqueStates = _.uniqBy(cs, 'state');
let result = uniqueStates.map(obj => obj['state']);
console.log(result);
Output:
We can observe the collection of distinct values associated with the state.
Conclusion:
We have understood the JavaScript array of unique objects in this article. We have comprehended methods that we can utilize to extract an array of unique objects. The methods which we have utilized are as follows:
- Set method
- reduce method
- map method
- filter and indexOfMethods
- map, set and from methods
- Lodash _.uniqBy method and map