Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading