Skip to content
Advertisement

Compare objects within an array and create a new array without duplicates

I’ve an array of objects:

[
  { name: "John", age: "34" },
  { name: "Ace", age: "14" },
  { name: "John", age: "45" },
  { name: "Harry", age: "11" },
]

I want to compare the objects within an array by name. If the duplicate name exists, I should compare the age and only keep the higher age object.

The expected output should be:

[
  { name: "Ace", age: "14" },
  { name: "John", age: "45" },
  { name: "Harry", age: "11" },
]

I am new to javascript/typescript and couldn’t find any optimal solution for this problem. I hope, I was able to explain my problem clearly.

Thanks.

Advertisement

Answer

try this

var objArr=...your json object;
var maxValueGroup = "name";
var maxValueName = "age";
console.log(JSON.stringify(newArr(objArr,maxValueGroup, maxValueName)));

newArr

var newArr = function (objArr,maxValueGroup, maxValueName) {
  var arr = groupBy(objArr, maxValueGroup);
  var newArr = [];
  $.each(arr, function (key) {
    var maxVal = 0;
    var maxValItem;
    arr[key].forEach((element) => {
      if (element[maxValueName] > maxVal) {
        maxVal = element[maxValueName];
        maxValItem = element;
      }
    });
    newArr.push(maxValItem);
  });
  return newArr;
};

groupby

var groupBy = function (xs, key) {
  return xs.reduce(function (rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement