Leonardo Lima
Leonardo Lima

Reputation: 646

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

I have an strng array.

e.g:

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?

Upvotes: 2

Views: 152

Answers (3)

Faizal Caba
Faizal Caba

Reputation: 89

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

Upvotes: 1

Isaac
Isaac

Reputation: 12874

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

Upvotes: 4

Mark
Mark

Reputation: 92440

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)

Upvotes: 2

Related Questions