javascript 在对象数组中查找具有 id 属性最大值的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22712691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find object having maximum value for the `id` property in an array of objects
提问by Krishanu Dey
In my array of objects, I want to find the object with the highest value for the id
property.
在我的对象数组中,我想找到id
属性值最高的对象。
Here is my array:
这是我的数组:
myArray = [
{
'id': '73',
'foo': 'bar'
},
{
'id': '45',
'foo': 'bar'
},
// …
];
Generally, I use $.grep
to find values in an array, like this:
通常,我用来$.grep
在数组中查找值,如下所示:
var result = $.grep(myArray, function (e) {
return e.id == 73;
});
But in this case I need to provide a specific id
value for the object I want to select.
但在这种情况下,我需要为id
要选择的对象提供特定值。
回答by Donal
Use the map()method of the array. Using map you can provide a function that iterates over every element in the array. In that function, you can work out the object with the highest id. For example:
使用数组的map()方法。使用 map 可以提供一个函数来遍历数组中的每个元素。在该函数中,您可以计算出具有最高 id 的对象。例如:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var maxid = 0;
myArray.map(function(obj){
if (obj.id > maxid) maxid = obj.id;
});
This will give you the max id of the objects in the array.
这将为您提供数组中对象的最大 id。
Then you can use grep to get the related object:
然后就可以使用grep来获取相关的对象:
var maxObj = $.grep(myArray, function(e){ return e.id == maxid; });
Alternatively, if you just want the object with the max id, you can do this:
或者,如果您只想要具有最大 id 的对象,您可以这样做:
var maxid = 0;
var maxobj;
myArray.map(function(obj){
if (obj.id > maxid) maxobj = obj;
});
//maxobj stores the object with the max id.
回答by mbcrute
The question states that he wants to find the objectwith the greatest id, not just the greatest id...
问题说他要找到id最大的对象,而不仅仅是id最大的...
var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
var max = myArray.reduce(function(prev, current) {
if (+current.id > +prev.id) {
return current;
} else {
return prev;
}
});
// max == {'id':'73','foo':'bar'}
回答by AbolfazlR
const students = [
{ id: 100, name: 'Abolfazl', family: 'Roshanzamir' },
{ id: 2, name: 'Andy', family: 'Madadian' },
{ id: 1500, name: 'Kouros', family: 'Shahmir' }
]
If you want to find the object with max Id:
如果要查找具有 max Id 的对象:
const item = students.reduce((prev, current) => (+prev.id > +current.id) ? prev : current)
// it returns { id: 1500, name: 'Kouros', family: 'Shahmir' }
If you want to find the object with min Id:
如果您想找到具有 min Id 的对象:
const item = students.reduce((prev, current) => (+prev.id < +current.id) ? prev : current)
// it returns {id: 2, name: "Andy", family: "Madadian"}
If you wnat to find the max Id:
如果您想找到最大 Id:
const max = Math.max.apply(null, students.map(item => item.id));
// it returns 1500
If you want to find the min Id:
如果你想找到min Id:
const min = Math.min.apply(null, students.map(item => item.id));
// it returns 2
回答by Ganesh
var max = 0;
var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]
var maxEle = myArray.map(function(ele){ if(ele.id>max){ max=ele} });
map is a function which iterates through array elements and performs specific operation.
map 是一个函数,它遍历数组元素并执行特定操作。
回答by Rochadsouza
Assuming that ID's are "stringified" numbers and achieving this by only use a map:
假设 ID 是“字符串化”数字并仅通过使用地图来实现这一点:
let arr = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}],
maxIndex = -1,
maxId;
arr.map(function(obj, i){
if(maxIndex === -1){
maxIndex = i;
maxId = Number(obj.id);
} else {
if (Number(obj.id) > maxId){
maxId = Number(obj.id);
maxIndex = i;
}
}
});
if(maxIndex !== -1) console.log(`Selected object: ${JSON.stringify(arr[maxIndex])}`)
else console.warn('No max ID. No ID\'s at all');
回答by Bergi
function reduceBy(reducer, acc) {
return function(by, arr) {
return arr[arr.reduce(function(acc, v, i) {
var b = by(v);
return reducer(acc[0], b) ? [b, i] : acc;
}, acc || [by(arr[0]), 0])[1]];
};
}
var maximumBy = reduceBy(function(a,b){return a<b;});
var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}];
console.log(maximumBy(function(x){
return parseInt(x.id,10)
}, myArray)); // {'id':'73','foo':'bar'}
回答by SummerRain
let id = items.reduce((maxId, item) => Math.max(maxId, item.id), 0);
or
或者
let id = Math.max(...items.map(item => item.id).concat(0)); // concat(0) for empty array
// slimmer and sleeker ;)
let id = Math.max(...items.map(item => item.id), 0);
This way is more practical, because in the case of an empty array, it returns 0, unlike
这种方式比较实用,因为在空数组的情况下,返回0,不像
Math.max.apply(null, [].map(item => item.id)) // -Infinity
and if you want to get "autoincrement", you can just add 1 regardless of whether the array is empty or not
如果你想获得“自动增量”,无论数组是否为空,你都可以加1
// starts at 1 if our array is empty
autoincrement = items.reduce((maxId, item) => Math.max(maxId, item.id), 0) + 1;
UPD:Code with map is shorter but with reduceis faster, which is felt with large arrays
UPD:带有 map 的代码更短,但带有reduce 的代码更快,这对于大数组来说是有感觉的
let items = Array(100000).fill()
.map((el, _, arr) => ({id: ~~(Math.random() * arr.length), name: 'Summer'}));
const n = 100;
console.time('reduce test');
for (let i = 1; i < n; ++i) {
let id = items.reduce((maxId, item) => Math.max(maxId, item.id), 0);
}
console.timeEnd('reduce test');
console.time('map test');
for (let i = 1; i < n; ++i) {
let id = Math.max(items.map(item => item.id).concat(0));
}
console.timeEnd('map test');
console.time('map spread test');
for (let i = 1; i < n; ++i) {
let id = Math.max(...items.map(item => item.id), 0);
}
console.timeEnd('map spread test');
reduce test: 163.373046875ms
map test: 1282.745849609375ms
map spread test: 242.4111328125ms
减少测试:163.373046875ms
地图测试:1282.745849609375ms
地图传播测试:242.4111328125ms
If we create an even larger array, spread map will shutdown
如果我们创建一个更大的数组,spread map 将关闭
let items = Array(200000).fill()
.map((el, _, arr) => ({id: ~~(Math.random() * arr.length), name: 'Summer'}));
reduce test: 312.43896484375ms
map test: 2941.87109375ms
Uncaught RangeError: Maximum call stack size exceeded at :15:32
减少测试:312.43896484375ms
映射测试:2941.87109375ms
Uncaught RangeError:最大调用堆栈大小超出:15:32