Sort an array in Javascript

Asked

Viewed 367 times

1

Hi. I have a problem, and I can’t seem to fix it. I have a text inside an array with several random letters.

Ex:"vwv rhjs vqgvcq pjdvb gjpsmc jsm zhctgvl jwgbbs" and so on, it’s 600 words.

I need to sort the words alphabetically, but not in the order of our alphabet. But this custom alphabet, the order of the letters is "k,b,w,r,q,d,n,f,x,j,m,l,v,h,t,c,g,z,p,s.

I already tried to pass everything to float, and try to sort with Sort(), but it didn’t work. Someone could help me with this?

  • Text within an array? Or each word is an element of the array?

  • So the text isn’t even in an array. It’s just text.. I put it in an array...

  • You’re missing letter on your order

  • 1

    In case are missing the letters "aeiouy"

  • So... but this custom alphabet, it’s just these letters... doesn’t have the other ones.

  • But the rest come before or after the ones you mentioned ?

Show 1 more comment

2 answers

1


Then you have to use a function by comparing the items according to the value of the position of the letters in the string you ordered. Using .indexOf() you find the position of the first letter in the index [0], but you will have to break the text of the array to use the .sort():

var string = ["sap vwv rhjs vqgvcq pjdvb pwzs gjpsmc jsm zhctgvl jwgbbs pwz"];
var alfa = "k,b,w,r,q,d,n,f,x,j,m,l,v,h,t,c,g,z,p,s";
string[0] = string[0].split(" ").sort(function(a, b){
   
   // faz uma comparação de tamanho da palavra para
   // fazer o laço "for" mais abaixo pela palavra que for maior
   var len = a.length > b.length || a.length == b.length ? a.length : b.length;
   
   // só faz o "return" quando uma letra for diferente da outra
   for(var x=0; x < len; x++){
      if(a[x] != b[x]) return alfa.indexOf(a[x])-alfa.indexOf(b[x]);
   }
   
}).join(" ");
console.log(string);

The string[0].split(" ") breaks the text of the index [0] array by white space.

The alfa.indexOf(a[x])-alfa.indexOf(b[x]) compares the position of the letters of each word by the previous one in the string alfa and assembles a new organized array, and the .join(" ") converts to string by separating array items by a space, assigning a new value to the string[0], now with the words in order.

  • So, it worked for the first letter... He ordered, but when the various words starting with the same letter, he does not order in the correct order.

  • I’m racking my brain here for the week interim, I couldn’t. Closest you could get was to turn everything to int with the index, and then try to compare with Sort() using a Function => P1-P2. However, when I turn everything into a number, it turns into an array like this : [1,12,13,2] and when I ask the Sort to compare two arrays like this, it can’t... but if I join the array, [12 2 12 2] then the Sort understands that it’s all one number only.

  • Look now.....

  • Ball show.. Thanks for the help...

  • Quiet! Know how to thank at this link ;)

0

  • Create a dictionary of letters in the order you want within a array;
  • Create a array with the normal letters of the alphabet;
  • Separate the words from the phrase you want with split by space;
  • Index the resulting words using the previously created dictionary, so you will have a array with words transformed into numbers. In your example you will have the following:

    [[12,2,12], [3,13,9,19], [12,4,16,12,15,4], [18,9,5,12,1], [16,9,18,19,10,15], [9,19,10], [17,13,15,14,16,12,11], [9,2,16,1,1,19]]
    
  • Make the equivalence between the generated indexes and the normal alphabet to get a list of equivalent words. In your example you will have the following:

    ['mcm', 'dnjt', 'meqmpe', 'sjfmb', 'qjstkp', 'jtk', 'rnpoqml', 'jcqbbt']
    
  • Use the sort to sort the resulting words, obtaining:

    ['dnjt', 'jcqbbt', 'jtk', 'mcm', 'meqmpe', 'qjstkp', 'rnpoqml', 'sjfmb']
    
  • Index the ordered equivalence and use the array dictionary to transform the indexes into words again, obtaining the following result after joining the array resulting in a new sentence:

    rhjs jwgbbs jsm vwv vqgvcq gjpsmc zhctgvl pjdvb
    

const DICIONARIO = ['k', 'b', 'w', 'r', 'q', 'd', 'n', 'f', 'x', 'j', 'm', 'l', 'v', 'h', 't', 'c', 'g', 'z', 'p', 's'];
const ALFABETO = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

const indexar = (referencia, palavra) => [...palavra].map((letra) => referencia.indexOf(letra));

const traduzir = (indices) => indices.map((indice) => DICIONARIO[parseInt(indice, 10)]).join('');

const ordenar = (frase) => {
  const indices = frase
    .split(' ')
    .map((palavra) => indexar(DICIONARIO, palavra));

  const equivalentes = indices.map((indice) => indice.map(posicao => ALFABETO[posicao]).join(''));

  equivalentes.sort();

  return equivalentes
    .map((palavra) => indexar(ALFABETO, palavra))
    .map(traduzir)
    .join(' ');
};

console.log(ordenar('vwv rhjs vqgvcq pjdvb gjpsmc jsm zhctgvl jwgbbs'));

  • Thank you very much.

  • @Rodolfomori if the answer helped you of a +1 in them

Browser other questions tagged

You are not signed in. Login or sign up in order to post.