Ikechukwu Orji
Ikechukwu Orji

Reputation: 3

creating an array of counts elements in an Array

I am trying to output an array that will give me the values of each count from the arr if the conditions hold true.

Example:

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

My code:

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
}   

Upvotes: 0

Views: 93

Answers (2)

Ori Drori
Ori Drori

Reputation: 191946

Reduce the deadlines array to the counts array:

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);

Upvotes: 1

IMTheNachoMan
IMTheNachoMan

Reputation: 5811

I think this is what you're looking for. You just want to count the number of instances each value in deadlines meets a certain criteria based on day.

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));

Upvotes: 0

Related Questions