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

Javascript .map() issue when taking array elements

I originally wrote this code to be preventing input field to submit value lesser than 0:

if (
    inflationArray[2].value < 0 ||
    inflationArray[1].value < 0 ||
    inflationArray[0].value < 0
  ) {
    alert("Can't input negative value");
    return;
  }

And it didn’t look like the best possible way to do it so I tried replacing it with this piece of code:

if (inflationArray.map((x) => x.value < 0)) {
    alert("Can't input negative value");
  }

Why is it not the same, did I not understand .map() correctly?
My only conclusion is that it might be because that the second way I wrote is not equal to the first one (If I am correct), but:

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

if (
    inflationArray[2].value < 0 &&
    inflationArray[1].value < 0 &&
    inflationArray[0].value < 0
  ) {
    alert("Can't input negative value");
    return;
  }

>Solution :

You’re looking for either Array.prototype.every() or Array.prototype.some().

This will test that every array-element has a value greater than zero, and return true if so (or false if not):

inflationArray.every((value) => value > 0);

Or, this can test that any of the array-elements hold a value of less-than zero; and return true if any one, or more, does (false if none are below zero):

inflationArray.some((value) => value < 0);

References:

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