简体   繁体   中英

Check if every element in array has a specfic value

I have an array with integers in it; and a function that returns a string. In this example, the function returns either 'solved' or 'unsolved' , based on the fact if a specific task was done before or not.

Now I need a way to call my function with every array element as parameter and check if the function returns 'solved' for every element.

Small example with real values:

var array1 = [2,5,8]; // 2 is solved, 5 is solved, 8 is unsolved
var array2 = [2,5,6]; // every element is solved

if (Function returns solved for every element) {
// array2 would be accepted for this part
}
else {
// array1 would go in this branch
}

Array.prototype.every()

The every() method tests whether all elements in the array pass the test implemented by the provided function.

If you already have a function that returns a string ( ie 'solved' or 'unsolved' ), then you can simply convert that to a boolean inside the callback you supply to .every() .

 var array1 = [2, 5, 8]; // 2 is solved, 5 is solved, 8 is unsolved var array2 = [2, 5, 6]; // every element is solved function isSolvedString(operand) { return operand < 8 ? 'solved' : 'unsolved'; } function isSolved(current) { return isSolvedString(current) === 'solved' ? true : false; } console.log(array1.every(isSolved)); // false console.log(array2.every(isSolved)); // true 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM