[英]Get the element in the array with the max value of a property using jQuery
I have an array of a custom JavaScript object which has a property named order
. 我有一个自定义JavaScript对象的数组,它有一个名为
order
的属性。 I have an array of this object, and I want to get the item with the highest "order". 我有一个这个对象的数组,我想得到具有最高“顺序”的项目。
Since I'm relatively new to jQuery, and coming from a C# background this is one of the instances where I highly appreciate LINQ :) 由于我对jQuery相对较新,并且来自C#背景,这是我非常欣赏LINQ :)的实例之一
Anyway, to cut a long story short, I've checked the following links but they only return the value and not a reference of the array element itself... So a little help in changing that to return the element would be appreciated. 无论如何,长话短说,我已经检查了以下链接,但他们只返回值而不是数组元素本身的引用...所以有一点帮助改变它返回元素将不胜感激。
jQuery min/max property from array of elements 来自元素数组的jQuery min / max属性
element with the max height from a set of elements 具有来自一组元素的最大高度的元素
The custom object in question(which I have an array of) is as follows: 有问题的自定义对象(我有一个数组)如下:
var severity = function (key, value, order) {
this.key = key;
this.value = value;
this.order = order;
};
Maybe I got you wrong... but is that you are looking for? 也许我弄错了你...但是你在找什么?
function getHighest(array) {
var max = {};
for (var i = 0; i < array.length; i++) {
if (array[i].order > (max.order || 0))
max = array[i];
}
return max;
}
// var array = [object, object, object ...];
var highest = getHighest(array);
DEMO: http://jsfiddle.net/c6gfj/ 演示: http : //jsfiddle.net/c6gfj/
Sort array and pop the last object in array 对数组进行排序并弹出数组中的最后一个对象
function sortObj(a, b){
return a.order < b.order ? 0 : 1;
}
obj.sort(sortObj)
var highest =obj.pop();
DEMO: http://jsfiddle.net/VaYNb/ 演示: http : //jsfiddle.net/VaYNb/
使用yourarray.sort()。它将按升序降序排序。对二维数组也有效。
array[array.map((o)=>o.order).indexOf(Math.max(...array.map((o)=>o.order)))]
let array=[{order:3},{order:5},{order:2},{order:2}]; console.log( array[array.map((o)=>o.order).indexOf(Math.max(...array.map((o)=>o.order)))] )
try this: 尝试这个:
function getHighest(array, value){
return array.sort(function(a,b){ b[value] - a[value] })[0];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.