简体   繁体   English

如何使用特定字母对字符串数组进行排序?

[英]How can I sort a string array using a specific alphabet?

I have an strng array. 我有一个strng数组。

eg: 例如:

StrArray = ["hook", "hour", "javascript", "nemo", "case"];

I know that if I use StrArray.Sort() it will sorted alphabetical. 我知道,如果我使用StrArray.Sort(),它将按字母顺序排序。 But I would to like to sort by using this alphabet = "jngmclqskrzfvbwpxdht" 但我想通过使用这个alphabet =“jngmclqskrzfvbwpxdht”来排序

I've searched but I only find people using HashTable to solve it. 我搜索过,但我发现只有人使用HashTable来解决它。

Is it possible to do in JS? 可以用JS做吗?

 let order = 'jngmclqskrzfvbwpxdht' let StrArray = ["hook", "javascript", "hour", "nemo", "case"]; StrArray.sort(function(a,b) { let firstAlphaOfParam1 = a.charAt(0); let firstAlphaOfParam2 = b.charAt(0); return order.indexOf(firstAlphaOfParam1) - order.indexOf(firstAlphaOfParam2); }) console.log(StrArray); 

The solution is only taking into consideration of sorting by only the first alphabet of element in StrArray . 该解决方案仅考虑仅通过StrArray中元素的第一个字母排序。 Basically we take the first alphabet and find the index in your jngmclqskrzfvbwpxdht and compare them 基本上我们采用第一个字母表并在jngmclqskrzfvbwpxdht找到索引并进行比较

Your sort vocabulary doesn't contain all the letters in you words, so it's not completely clear how to proceed with words like 'hour' and 'hook' as there's no 'o' in the sort list. 你的排序词汇表中没有包含你单词中的所有字母,所以如果在排序列表中没有'o',那么如何继续使用'hour'和'hook'这样的单词并不完全清楚。 You can just ignore them and treat anything that isn't in the list as equal in the sort order. 您可以忽略它们,并在排序顺序中将列表中不存在的任何内容视为相等。 You also should test against similar bases like "hook" and "hooks" 您还应该测试类似的基础,如“钩子”和“钩子”

For example: 例如:

 let StrArray = ["hook", "javascript", "nemo", "hours", "case", "hour", "houn"]; const sort_order = "jngmclqskrzfvbwpxdht" StrArray.sort((a, b) => { let i = 0; while (i < a.length && i < b.length ){ let a_i = sort_order.indexOf(a[i]), b_i = sort_order.indexOf(b[i]); if (a_i === b_i ) { i++ continue } return a_i - b_i } // one is a substring of the other, sort by length return a.length - b.length }) console.log(StrArray) 

I can leave a small contribution, this code can sort using the first letter. 我可以留下一点贡献,这段代码可以使用第一个字母排序。

 var arr1 = ["hook", "javascript", "nemo", "case"]; var myAbc = 'jngmclqskrzfvbwpxdht'; var final_array = []; for (i = 0; i < myAbc.length; i++) { for (j = 0; j < arr1.length; j++) { if (arr1[j].charAt(0) == myAbc.charAt(i)) { final_array.push(arr1[j]); } } }; console.log(final_array); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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