简体   繁体   English

如何使用JavaScript中的比较器选择数组中的最小/最大元素?

[英]How to select the min/max element in an array using comparator in JavaScript?

I want to find the largest element in an array. 我想在数组中找到最大的元素。 For example, finding the person with the highest salary. 例如,找到薪水最高的人。 I can sort the array using a salary comparator, but it is inefficient. 我可以使用工资比较器对数组进行排序,但是效率不高。 What is the simplest and best way to do this? 最简单,最好的方法是什么?

For reference, I can do this in Python as follows. 作为参考,我可以在Python中执行以下操作。

heapq.nlargest(1, [array_of_whatever], comparator)[0]

This is what I would do: 这就是我要做的:

 const maxBy = (comparator, array) => array.reduce((acc, val) => comparator(acc, val) > 0 ? acc : val); const employees = [ { name: "Alice", salary: 1000 } , { name: "Bob", salary: 2000 } , { name: "Charlie", salary: 1500 } ]; const salaryComparator = (a, b) => a.salary - b.salary; const max = maxBy(salaryComparator, employees); console.log(max); 

Is this what you're looking for? 这是您要找的东西吗?

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

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