![](/img/trans.png)
[英]Find objects having 3 maximum value for the `albumId` property in an array of objects e.g 100,99,98
[英]Find object having maximum value for the `id` property in an array of objects
在我的对象数组中,我想找到id
属性值最高的对象。
这是我的数组:
myArray = [
{
'id': '73',
'foo': 'bar'
},
{
'id': '45',
'foo': 'bar'
},
// …
];
通常,我使用$.grep
在数组中查找值,如下所示:
var result = $.grep(myArray, function (e) {
return e.id == 73;
});
但在这种情况下,我需要为要选择的对象提供特定的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'}
使用数组的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;
});
这将为您提供数组中对象的最大 id。
然后就可以使用grep来获取相关的对象:
var maxObj = $.grep(myArray, function(e){ return e.id == maxid; });
或者,如果您只想要具有最大 id 的对象,您可以这样做:
var maxid = 0;
var maxobj;
myArray.map(function(obj){
if (obj.id > maxid) maxobj = obj;
});
//maxobj stores the object with the max id.
const students = [
{ id: 100, name: 'Abolfazl', family: 'Roshanzamir' },
{ id: 2, name: 'Andy', family: 'Madadian' },
{ id: 1500, name: 'Kouros', family: 'Shahmir' }
]
如果要查找具有 max Id 的对象:
const item = students.reduce((prev, current) => (+prev.id > +current.id) ? prev : current)
// it returns { id: 1500, name: 'Kouros', family: 'Shahmir' }
如果您想找到具有 min Id 的对象:
const item = students.reduce((prev, current) => (+prev.id < +current.id) ? prev : current)
// it returns {id: 2, name: "Andy", family: "Madadian"}
如果您想找到最大 Id :
const max = Math.max.apply(null, students.map(item => item.id));
// it returns 1500
如果你想找到min Id :
const min = Math.min.apply(null, students.map(item => item.id));
// it returns 2
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'}
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 是一个遍历数组元素并执行特定操作的函数。
let id = items.reduce((maxId, item) => Math.max(maxId, item.id), 0);
或者
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);
这种方式比较实用,因为在空数组的情况下,返回0,不像
Math.max.apply(null, [].map(item => item.id)) // -Infinity
如果你想获得“自动增量”,无论数组是否为空,你都可以加1
// starts at 1 if our array is empty
autoincrement = items.reduce((maxId, item) => Math.max(maxId, item.id), 0) + 1;
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');
减少测试:163.373046875ms
地图测试:1282.745849609375ms
地图传播测试:242.4111328125ms
如果我们创建一个更大的数组,spread map 将关闭
let items = Array(200000).fill()
.map((el, _, arr) => ({id: ~~(Math.random() * arr.length), name: 'Summer'}));
减少测试:312.43896484375ms
地图测试:2941.87109375ms
未捕获的 RangeError:在 15:32 时超出了最大调用堆栈大小
假设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');
使用reduce()
的缩短版本
myArray.reduce((max, cur)=>(max.likes>cur.likes?max:cur))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.