I’ve an array of objects:
JavaScript
x
7
1
[
2
{ name: "John", age: "34" },
3
{ name: "Ace", age: "14" },
4
{ name: "John", age: "45" },
5
{ name: "Harry", age: "11" },
6
]
7
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:
JavaScript
1
6
1
[
2
{ name: "Ace", age: "14" },
3
{ name: "John", age: "45" },
4
{ name: "Harry", age: "11" },
5
]
6
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
JavaScript
1
5
1
var objArr=your json object;
2
var maxValueGroup = "name";
3
var maxValueName = "age";
4
console.log(JSON.stringify(newArr(objArr,maxValueGroup, maxValueName)));
5
newArr
JavaScript
1
17
17
1
var newArr = function (objArr,maxValueGroup, maxValueName) {
2
var arr = groupBy(objArr, maxValueGroup);
3
var newArr = [];
4
$.each(arr, function (key) {
5
var maxVal = 0;
6
var maxValItem;
7
arr[key].forEach((element) => {
8
if (element[maxValueName] > maxVal) {
9
maxVal = element[maxValueName];
10
maxValItem = element;
11
}
12
});
13
newArr.push(maxValItem);
14
});
15
return newArr;
16
};
17
groupby
JavaScript
1
7
1
var groupBy = function (xs, key) {
2
return xs.reduce(function (rv, x) {
3
(rv[x[key]] = rv[x[key]] || []).push(x);
4
return rv;
5
}, {});
6
};
7