Skip to content
Advertisement

array.every() works on only first element

I have an array

errorPriority: string[] = ['shippingError', 'paymentInfoError', 'generalError'];

I need a function call to be looped on every element of array, but somehow after executing function for first element ‘shippingError’, the loop stops. Below is the function call

this.errorPriority.every(this.getErrorData);

And the function that is executed

getErrorData = (value: string): void => {
    if (eval(this.objectPath[value as keyof ObjectPath]) && eval(this.objectPath[value as keyof ObjectPath]).length)
      this.checkoutState.errors[value] = eval(this.objectPath[value as keyof ObjectPath]);
  }

It sometimes, works on array element, but mostly stops after first element, Am I missing something, please help

I expect function should be looped on every array element

Advertisement

Answer

from the MDN documentation the definition of array.every() is

every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

so array.every returns a boolean. in your code you don’t return anything. if the condition is true, you only assign a new property.

the following should work:

   getErrorData = (value) => {
    if (eval(this.objectPath[value]) && eval(this.objectPath[value]).length) {
      this.checkoutState.errors[value] = eval(this.objectPath[value]);
      return true;
    }
      return false
    }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement