Catch duplicate attributes within an array of objects and retrieve unique elements.
Array/object in question -
1
2
3
4
5
6
|
const students = [
{ name: "Rama", grade: 10 },
{ name: "Kris", grade: 5 },
{ name: "Pete", grade: 7 },
{ name: "Mo", grade: 5 }
];
|
We want to get unique grades from the array.
Option 1: Quickest way - use set
Use a set to get unique values. We had a quick post on sets in Javascript just yesterday.
1
2
|
const uniqueGradesSet = [...new Set(students.map(stu => stu["grade"]))];
console.log("uniqueGradesSet: ", uniqueGradesSet); // [ 10, 5, 7 ]
|
Option 2: Use object + array combination
Use an object with each iteration to check and filter duplicates.
1
2
3
4
5
6
7
8
9
10
|
const uniqueGrades = [];
const duplicateCatcher = {};
students.forEach(stu => {
if (!duplicateCatcher[stu.grade]) {
uniqueGrades.push(stu.grade);
duplicateCatcher[stu.grade] = "ok";
}
});
console.log(uniqueGrades); // [ 10, 5, 7 ]
|