1

This function is only returning true. I have added a console.log in the if block and it is called but the function doesn't return false.

function isUniform(List)
{
    var ele = List[0];
    List.forEach(function(item)
    {
        console.log(ele);
        if(ele !== item)
        {
            return false;
        }
    })
    return true;
}
  • 1
    what does this list have? – Vinay Pratap Singh Bhadauria Apr 18 '17 at 10:19
  • 1
    What are is the value of `ele`/`item`? – Tom Apr 18 '17 at 10:20
  • Just some numbers like [1,2,2,2] – Ahmed Hassan Apr 18 '17 at 10:21
  • 1
    Possible duplicate of [How to short circuit Array.forEach like calling break?](http://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break) – JJJ Apr 18 '17 at 10:21
  • Post a minimal verifiable example. [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Pugazh Apr 18 '17 at 10:22
  • ele is always equal to first element of the list and then it is compared with every element of list through a foreach loop @thebluefox – Ahmed Hassan Apr 18 '17 at 10:22
  • @Vamsi yes for the first element it will be equal but then for the rest of the elements it is not equal. – Ahmed Hassan Apr 18 '17 at 10:23
  • Quick Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead. Taken from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Saugat Apr 18 '17 at 10:24
  • @JJJ so you are saying return false will not return the function and foreach will still run despite the return statement? – Ahmed Hassan Apr 18 '17 at 10:24

2 Answers2

9

You need another method for testing unifomity. Better use Array#every, which checks every value with the first item of the array and return true, if all elements are equal and false if not. The iteration stops with the first unequal element.

function isUniform(list) {
    return list.every(function(item, _, array) {
        return item === array[0];
    });
}

The used Array#forEach returns always undefined:

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

I think you can use this code;

function isUniform(List)
{
    var res = true;
    var ele = List[0];
    List.forEach(function(item)
    {
        console.log(ele);
        if(ele !== item)
        {
            res = false;
            return;
        }
    })
    return res;
}
muratoner
  • 2,316
  • 3
  • 20
  • 32