Martin WasGehtSieDasAn Martin WasGehtSieDasAn - 14 days ago 5
Javascript Question

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
}

Answer

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

Comments