简体   繁体   中英

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

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 (""))

You are referring arr[1] which is not available also you have to split in order to sort the letters.

 var arr = ["cinema"]; var sorted = arr[0].split('').sort(); console.log(sorted, sorted.join('')); 

This should do what you want:

var arr = ["cinema"];

console.log(arr[0].split("").sort().join(""));

EDIT: I see the same solution has been proposed by several others. I'll expand a bit on it.

Since you want to sort by the letters in the word cinema, and cinema is at index 0, you get the string "cinema" by calling arr[0], and then split the string with the method .split(""). This turns the string into an array that you can .sort() in the way you attempted initially.

The error you got, "Error: arr[1].sort is not a function", tells you that .sort() is not a function of the string element. Once you've turned the string into an array (for example with .split()), the .sort() function becomes available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM