0

Heres my code. I don't really know what I'm doing wrong.

var arr = [{
   order_count: 1,
   order_date: "2015-10-10"

}, {
    order_count: 2,
    order_date: "2017-03-01"
}, {
    order_count: 3,
    order_date: '2017-04-10'
}];

function checkDay (date, maxDays){
   var flag = false;
   arr.forEach(function(element) {
     if (element.order_date === date && element.order_count >= maxDays)
     {
      flag = true;
      return true;
     }
   });
   if (!flag) {
    return false;
   }
}

console.log(checkDay('2017-04-10', 3));
Isaac
  • 11,409
  • 5
  • 33
  • 45
Paola Reyes
  • 152
  • 2
  • 12
  • 2
    because `checkDay` doesn't return anything when flag is true ... just `return flag` ... oh, and `return true` in forEach does not stop the forEach ... perhaps you want to look at array methods like `.some` or `.every` for loops that **can** terminate early – Jaromanda X Feb 21 '18 at 00:44
  • You really should be using some() not forEach() – epascarello Feb 21 '18 at 00:47
  • 1
    https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function/34653650 – epascarello Feb 21 '18 at 00:48

3 Answers3

3

The return true inside your arr.forEach only breaks out of the current iteration inside the forEach (other iterations will continue to be executed), not the main function.

Change

if (!flag) {
 return false;
}

to

return flag;
Isaac
  • 11,409
  • 5
  • 33
  • 45
3

Use array.some method

function checkDay(date, maxDays) {
    return arr.some(element => element.order_date === date && element.order_count >= maxDays);
}

This will only loop until either all elements are processed and evaluated false, or finish looping once a true is returned - so, the behaviour is exactly as you expected

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

You're not returning a value

function checkDay (date, maxDays) {
   var flag = false;

   arr.forEach(function(element) {
     if (element.order_date === date && element.order_count >= maxDays) {
      flag = true;
     }
   });

   return flag;
}

A better approach using the function some

function checkDay (date, maxDays) {
  return arr.some((element) => element.order_date === date && element.order_count >= maxDays);       
}

Resource

  • Array.prototype.some()

    The some() method tests whether at least one element in the array passes the test implemented by the provided function.

Ele
  • 33,468
  • 7
  • 37
  • 75