![](/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.