我有一个问题,我试图计算有多少个 child 的年龄(作为关键),如下所示,但我们想要 根据 a 获取大 child 组(在本例中是大 child 的组是 4 和 2) child >= 4 个 child 组我想获得可以组成大 child 组的最大年龄数。
问题我如何获得新创建的组中最大年龄小于/等于 4 个 child 的年龄?
这就是我们在输入中得到的内容
max_bigest_kids_in_group = 4
kids object = {
//age 0 have 7 kids
'0' : 7
//age 1 have 3 kids
'1' : 3
//age 2 have 2 kids
'2' : 2
//age 4 have 1 kids
'4' : 1
//lets say there is no age 3 or 5,6 and so on.
}
这是我目前在 psudo 中尝试过并目前所做的
try biggest next biggest
('4' = 1) + ('2' = 2) (oke becouse 1+2 is 3 >= 4) save array [4 and 2]
try biggest next biggest next biggest
('4' = 1) + ('2' = 2) + ('1' = 3) (not oke becouse 1+2+3 is 6 >= 4) stop becouse its more then x = 4
get array [4 and 2]
// expected result is {'4','2'} or ['4','2'] so if max_bigest_kids_in_group = 6 then it will be ['4','2','1']
我们怎样才能得到预期的结果?在 JavaScript 中
ps。抱歉,如果标题不准确,如果有任何建议,请评论或编辑。
最佳答案
这很简单。只需对 children 进行循环,就像在伪代码中一样。
var kids = {
'0' : 7, //age 0 have 7 kids
'1' : 3, //age 1 have 3 kids
'2' : 2, //age 2 have 2 kids
'4' : 1 //age 4 have 1 kids
};
function getAgesOfOldestKids(n) {
/* get: {number} how many kids */
// lets begin with some magic to find out the maximum age in the set
// you might code this with a for-in-loop over kids
var max = Math.max.apply(null, Object.keys(kids));
var ages = []; // ages of the kids in the result
var count = 0; // how many kids are in the set
for (var i=max; i>=0; i--)
if (i in kids) { // age level exists
count += kids[i]; // add number of kids
if (count > n) // kids in the set are more than allowed
return ages; // break the loop
else
ages.push(i); // add this age step to the result
}
return ages; // there may be less children than requested
}
> getAgesOfOldestKids(4)
["4", "2"]
// a trick to get the number of kids in the result:
> var ages = [4, 2];
> ages.reduce(function(n, age){return n+kids[age]}, 0)
3
其他可能且更短的解决方案,直接在 child 的 key 上循环:
function getAgesOfOldestKids(n) {
/* get: {number} how many kids */
// ages, sorted descending
var ages = Object.keys(kids).sort(function(a,b){return b-a;});
var count = 0; // how many kids are in the set
for (var i=0; i<ages.length-1 && count <= n; i++)
count += kids[ages[i]]; // add number of kids
return ages.slice(0, i-1);
}
关于javascript - 获取在javascript中值叠加仍然较少的数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414113/