EN
JavaScript - equivalents of Python any() and all() functions?
1 answers
0 points
Are there any equivalents of Python any()
and all()
functions in JavaScript?
I need methods which can be applied on a list (array) as following:
any()
- returnstrue
if any element of the iterable istrue
. If the iterable is empty, returnsfalse
.all()
- returnstrue
if all elements of the iterable aretrue
, or if the iterable is empty.
Are there any equivalent built-in functions available in JavaScript?
1 answer
0 points
You can implement a custom any()
and all()
methods using simple for loop combined with if statement.
Practical example
1. any()
function:
xxxxxxxxxx
1
const any = (array) => {
2
for (let i = 0; i < array.length; ++i) {
3
if (array[i]) return true;
4
}
5
return false;
6
};
2. all()
function:
xxxxxxxxxx
1
const all = (array) => {
2
for (let i = 0; i < array.length; ++i) {
3
if (!array[i]) return false;
4
}
5
return true;
6
};
0 commentsShow commentsAdd comment