简体   繁体   中英

How can I sort a string array using a specific alphabet?

I have an strng array.

eg:

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

I know that if I use StrArray.Sort() it will sorted alphabetical. But I would to like to sort by using this alphabet = "jngmclqskrzfvbwpxdht"

I've searched but I only find people using HashTable to solve it.

Is it possible to do in 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 . Basically we take the first alphabet and find the index in your jngmclqskrzfvbwpxdht and compare them

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

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