Martin WasGehtSieDasAn
Martin WasGehtSieDasAn

Reputation: 305

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
}

Upvotes: 2

Views: 1441

Answers (1)

gfullam
gfullam

Reputation: 12045

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 (i.e. '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

Upvotes: 4

Related Questions