Search code examples
javascriptarraysmap-function

Return an element using `array.some()` instead of boolean


I'm trying to use an array.some function to iterate through some data and return my field if the if statement succeeds.

What I am finding is happening instead, is that I am getting a boolean return e.g true instead of the actual variable (which contains details to an element).

for (var index in allFields) {
      const invalidField = allFields[index].some(function (field){
        if (!validation.getIn([index,field.dataset.fieldKey,'isValid'])) {
          return field;
        }
      });
      if (invalidField) {
        return invalidField;
      }
    }

My code cycles through allFields, which contains lists of fields under indexes. It then compares each fieldKey with another set of data called validation.

field contains an element. I wish to return field but instead when I check invalidField I get true instead of the element


Solution

  • Array.prototype.some() only checks if any element in the array passes test defined in callback function. You should use array find method which returns first element passig test