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

How to convert char to int in array (JavaScript)

How to change char value in array to int value? and detect first element and second element in array

arr = [a,a,a,b,b,a,b]

first element = a

second element = b

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

a = 1, b = 2

My expected output

arr = [1,1,1,2,2,1,2]

>Solution :

You can do it like so.

You can only get the char code of an index in a string. Since we have an char array we can alsways get the index of 0.
The smallest charcode is of A which is 65. In this example I transform a to A which resolves to 65 then I remove 64 since a should be 1. Consecutively b is mapped to B which is 65 and resolves to 2 since 64 is removed

const arr = ['a','a','a','b','b','a','b']


const res = arr.map(char => char.toUpperCase().charCodeAt(0) - 64)
console.log(res)
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