[英]Return object with highest key/value pairs from an array of objects
Given an array of objects, I want to return an object with the highest values from all the objects. 给定一个对象数组,我想从所有对象中返回一个具有最高值的对象。
let countObj = [{2:1},{2:4, 5:1},{3:3}]
let finalObj = {}
let primes = [2,3,5]
// finalObj should return {2:4, 3:3, 5:1}
I feel like there should be some way to use the primes array and reduce on the countObj to get the desired result. 我觉得应该有某种方法可以使用质数数组并减少countObj以获得所需的结果。
primes.forEach(p => countObj.reduce((a,b) =>{
if (a[p]){ //if prime no. exists as key in a
a[p] > b[p] ? //keep key/val pair in a : replace key/val pair
}else{ //if new prime is not a key in a
a[p] = b[p]
}
},{})
I'm not sure if the logic is correct and also, I don't know how to get it to return the final object. 我不确定逻辑是否正确,而且我也不知道如何获取它以返回最终对象。
Be careful with your tests: 0 is the same as a missing value. 测试时要小心:0等于缺失值。 And when using
reduce
, you must return the accumulator object. 并且在使用
reduce
,必须返回累加器对象。
I'd reduce on the objects instead of reducing on the primes: 我会减少对象而不是减少素数:
let finalObj = countObj.reduce((f, o)=>{
primes.forEach(k=>{
if (k in o && !(o[k]<f[k])) f[k]=o[k];
});
return f;
}, {});
You could check if the stored value is greater than the actual value and if not, then assign the value to the result set. 您可以检查存储的值是否大于实际值,如果不是,则将该值分配给结果集。
var countObj = [{ 2: 1 }, { 2: 4, 5: 1 }, { 3: 3 }], finalObj = {}; countObj.forEach(o => Object.keys(o).forEach(k => finalObj[k] > o[k] || (finalObj[k] = o[k]))); console.log(finalObj); // { 2:4, 3: 3, 5: 1 }
With primes
primes
var countObj = [{ 2: 1 }, { 2: 4, 5: 1 }, { 3: 3 }], finalObj = {}, primes = [2, 3, 5] countObj.forEach(o => primes.forEach(k => k in o && (finalObj[k] > o[k] || (finalObj[k] = o[k])))); console.log(finalObj); // { 2:4, 3: 3, 5: 1 }
You can use a nested foreach
like this. 您可以像这样使用嵌套的
foreach
。
In this case you do not need primes[]
在这种情况下,您不需要
primes[]
let countObj = [{ 2: 1 }, { 2: 4, 5: 1 }, { 3: 3 }]; let finalObj = {}; let primes = [2, 3, 5]; countObj.forEach(function(obj) { Object.keys(obj).forEach(function(key) { var finalObjValue = finalObj[key] || 0; if(obj[key] > finalObjValue) finalObj[key] = obj[key]; }); }); console.log(finalObj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.