Catch duplicate attributes within an array of objects and retrieve unique elements.

Array/object in question -

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.

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.

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 ]