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

Use String functions on an element while using map() on array in javascript?

I am trying to do the following.

strs = ["one", "two"];
let sorted_str = strs.map((s) => [s.sort(), s]);

Essentially, what I am trying to do is create a new array of arrays, where this new array is like [sorted string from first array, original string from first array]

However, it looks like the .sort() method is not valid here.

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

I even tried making it

let sorted_str = strs.map((s) => [s.toString().sort(), s]);

to force a String and make sure it has a sort() method possible, but to no avail.

The error is TypeError: s.toString(...).sort is not a function.

Any way I can get this to work or any simple workaround will be appreciated.

>Solution :

You need to get an array of characters, sort it and get a string back.

const
    strs = ["one", "two"],
    sorted_str = strs.map((s) => [Array.from(s).sort().join(''), s]);

console.log(sorted_str);
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