在数组中创建计数元素数组

时间:2016-11-17 22:01:10

标签: javascript arrays

我正在尝试输出一个数组,如果条件成立,它将从arr中给出每个计数的值。

示例:

//tasksTypes([1, 2, 4, 2, 10, 3, 1, 4, 5, 4, 9, 8], 1)  [2, 8, 2]

我的代码:

function tasksTypes(deadlines, day) {
    var list= [];
    var today = 0;
    var upcoming = 0;
    var later = 0;

    for(var i=0; i<deadlines.length; i++){
        if(deadlines[i] <= day){
            today += today
            list.push(today)
            if(deadlines[i] <= day + 7){
                upcoming += upcoming
                list.push(upcoming)
                if(deadlines[i] > day + 7){
                    later += later
                    list.push(later)
                }
            }
        }
    }
    return list
}   

2 个答案:

答案 0 :(得分:1)

将截止日期数组减少到count数组:

function tasksTypes(deadlines, day) {
  return deadlines.reduce(function(counts, deadline) {
    var index = deadline <= day ? 0 : (deadline <= day + 7 ? 1 : 2);
    
    counts[index]++;
    
    return counts;
  }, [0, 0, 0]);
}

var result = tasksTypes([1, 2, 4, 2, 10, 3, 1, 4, 5, 4, 9, 8], 1);

console.log(result);

答案 1 :(得分:0)

我认为这是你正在寻找的东西。您只想根据deadlines计算day中每个值符合特定条件的实例数。

&#13;
&#13;
function tasksTypes(deadlines, day) {
  var today = 0;
  var upcoming = 0;
  var later = 0;
  
  for(var i = 0; i < deadlines.length; ++i) {
    if(deadlines[i] <= day)
        today++;
    else if(deadlines[i] <= day + 7)
        upcoming++;
    else
        later++;
   }
  
  return [today, upcoming, later];
}

console.log(tasksTypes([1, 2, 4, 2, 10, 3, 1, 4, 5, 4, 9, 8], 1));
&#13;
&#13;
&#13;