Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using method sort() for sorting symbols in element of array

I need to sort an element cinema of array arr by symbols unicode (in the output it must been like "aceinm"). I know that in this case we need to use method sort(). But I do know how inject sort method for array element.

Please, help. Code below are not working.

Error: arr[1].sort is not a function.

var arr = ["cinema"];

arr[1].sort();
console.log(arr[1]);
like image 278
Sviat Kuzhelev Avatar asked Jan 20 '26 15:01

Sviat Kuzhelev


1 Answers

If you want to sort your string, you can easily do this by splitting and joining the string.

"cinema".split ("").sort ().join ("")
// aceimn

Or, in your case:

arr[0] = arr [0].split ("").sort ().join ("")
// arr: ["aceimn"]

If you need to sort all strings in an array, use map ().

arr = arr.map (itm => itm.split ("").sort ().join (""))
like image 185
NikxDa Avatar answered Jan 23 '26 03:01

NikxDa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!