按特定字母对JS字符串数组进行排序 [英] sort a JS string array by a specific letter

查看:56
本文介绍了按特定字母对JS字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须对这样的字符串数组进行排序:

I have to sort an array of strings like this:

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

排序类型必须为特定字母,在这种情况下为W,因此我的函数必须返回此数组:

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

这是一个动态数组,我不知道数组中的单词数,如果每个单词都没有字母W,一个W或某个W.

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?

谢谢!

推荐答案

只需比较字母的索引即可.

Just compare the index of the letter.

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

演示: http://jsfiddle.net/KrqmM

waka
kawa
akwa
akaw

这篇关于按特定字母对JS字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆