Sort object descending in Java

Asked

Viewed 121 times

2

I need to sort descending the following object and after that I must delete everything that comes after "_" and even him, to see which word is formed:

Follow what I’ve done:

var str = 'string muito grande para o comentário';
var count = {};

str.split('').forEach(function(v) {

 if (v === ' ') return;
 v = v.toLowerCase();
 count[v] = count[v] ? count[v] + 1 : 1; 

}); 

console.log(count);


count{
    a:94 
    b:93
    c:88
    d:87
    e:91
    f:86
    g:80
    h:83
    i:78
    j:79
    k:82
    l:92
    m:74
    n:99
    o:96
    p:98
    q:84
    r:97
    s:77
    t:81
    u:100
    v:95
    w:75
    x:89
    y:85
    z:76
    _:90
}
  • You look like you should do... what have you done? Where is your doubt?

  • I just counted how many times each letter appeared in this string this and arrived at that result, but now I need to do what is there in the description of the question. I got to it like this: var str = 'too big a string for the comment'; var Count = {}; str.split('). foreach(Function(v) { if (v === ' ') Return; v = v.toLowerCase(); Count[v] = Count[v] ? Count[v] + 1 : 1; }) console.log(Count);

  • Put your comment code there in the question

  • @Sabrinab. I put an answer based on the comment. Ideal is that your code be added to the question.

1 answer

2


As your ultimate goal is to get the word, just use the function below:

var str = 'string muito grande para o _ comentário'; 
var count = {}; 


str.split('').forEach(function(v) { 
	if (v === ' ') 
		return; 
	v = v.toLowerCase(); 
	count[v] = count[v] ? count[v] + 1 : 1; 
}) 

function palavra(hashTable){
  return Object.keys(hashTable).sort(function(a, b){
    //Ordenacao decrescente
    return hashTable[b] - hashTable[a];

  }).reduce(function(p, c){ 
      //Formacao da palavra
      return p+c
  }).split('_')[0];//Texto antes de _
  
}

console.log(palavra(count))

  • 1

    It really worked, I did the table test is correct. Thank you so much!

  • @Sabrinab. So mark my answer as right, please.

Browser other questions tagged

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