Skip to content Skip to sidebar Skip to footer

What Is The Equivalent Of Python Any() And All() Functions In Javascript?

Python does has built in functions any() and all(), which are applied on a list(array in JavaScript) as following- any(): Return True if any element of the iterable is true. If the

Solution 1:

The Python documentation gives you pure-python equivalents for both functions; they are trivial to translate to JavaScript:

functionany(iterable) {
    for (var index = 0; index < iterable.length; index++) {
        if (iterable[index]) returntrue;
    }
    returnfalse;
}

and

functionall(iterable) {
    for (var index = 0; index < iterable.length; index++) {
        if (!iterable[index]) returnfalse;
    }
    returntrue;
}

Recent browser versions (implementing ECMAScript 5.1, Firefox 1.5+, Chrome, Edge 12+ and IE 9) have native support in the form of Array.some and Array.every; these take a callback that determines if something is 'true' or not:

some_array.some((elem) => !!elem );
some_array.every((elem) => !!elem );

The Mozilla documentation I linked to has polyfills included to recreate these two methods in other JS implementations.

Solution 2:

You can use lodash.

lodash.every is equivalent to all

lodash.some is equivalent to any

Solution 3:

Build-in function some is equivalent to any I suppose.

constarray = [1, 2, 3, 4, 5];

const even = function(element) {
  // checks whether an element is evenreturn element % 2 === 0;
};

console.log(array.some(even));
// expected output: true

You can read more in the docs

Post a Comment for "What Is The Equivalent Of Python Any() And All() Functions In Javascript?"