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 regex on array

I currently have this example array:

array = [1.2%, 16%, 9.0%, 8%]

I want to get the highest number so I did this:

Math.max.apply(null, array);

But it shows an error maybe because of the ‘%’

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

How can I filter the array using regex? It’s my first time using regex on the array. I already spent more than 2 hours I still don’t get it.

Here are my works that did not work:

array = [1.2%, 16%, 9.0%, 8%].match(/[0-9]*\.?[0-9]/);
array = [1.2%, 16%, 9.0%, 8%].replace(/[0-9]*\.?[0-9]/);
array = [1.2%, 16%, 9.0%, 8%].match(/[\d]+/);

Sorry I am new to javascript. Thanks.

>Solution :

You can map the strings to parseFloat, then the "%" will be ignored:

let array = ["1.2%", "16%", "9.0%", "8%"];

let result = Math.max(...array.map(parseFloat));

console.log(result);

NB: I used the spread syntax here instead of apply, just because that is the more modern way to write it (since EcmaScript 2015).

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