sort a JS string array by a specific letter

…衆ロ難τιáo~ 提交于 2020-12-10 07:54:04

问题


I have to sort an array of strings like this:

var arr = ["akaw","waka","kawa","akwa"];

The type of sort must be by a specific letter, W in this case so my function must return this array:

arr = ["waka","kawa","akwa","akaw"];

It's a dynamic array and I don't know the number of words in array and if each words have no letter W, one W or some W.

Do you know a type of sort function to do that?

Thx!


回答1:


Just compare the index of the letter.

arr.sort(function(a,b) {
    return a.indexOf("w") - b.indexOf("w");
})

DEMO: http://jsfiddle.net/KrqmM

waka
kawa
akwa
akaw


来源:https://stackoverflow.com/questions/17118818/sort-a-js-string-array-by-a-specific-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!