简体   繁体   English

比较数组中的对象字段

[英]Compare the object fields within array

Compare the age of the objects in an array and keep only the one with the highest age.比较数组中对象的年龄,只保留年龄最大的对象。 I've gone through the solution which uses reduce function, but is there any other optimal way other than using reduce?我已经完成了使用reduce函数的解决方案,但是除了使用reduce之外还有其他最佳方法吗? I am new to javascript, and still learning the concepts.我是 javascript 新手,仍在学习这些概念。

array: [ { "name": "sample", "age": 22 },{ "name": "sample2", "age": 42 }]

You can achieve this with sort:您可以通过排序实现此目的:

 const array = [ { "name": "sample", "age": 22 },{ "name": "sample2", "age": 42 }] const max = array.sort((a, b) => { return b.age - a.age })[0] console.log([max])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM