Home > Software engineering >  Use String functions on an element while using map() on array in javascript?
Use String functions on an element while using map() on array in javascript?

Time:07-04

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.

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.

CodePudding user response:

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);

CodePudding user response:

You need to convert to array, then apply the sort method, and then join to a string again, try this:

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

console.log(sorted_str);

CodePudding user response:

instead of using split(). do not use split()

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

console.log(sorted_str)

CodePudding user response:

The String class does not have a .sort() method. The array class does, though! So you can convert the string to an array, sort that, and then convert the sorted array back to a string. That would look something like

s.split("").sort().join("")
  • Related