重复的数字计数结果为升序

时间:2015-10-29 12:40:44

标签: javascript arrays sorting

我试图在升序中计算结果

以下是我的代码

  var NewArray = [1,4,5,2,1,3,4,2,4,5,6,4,2,1,7];
  var SortNewArray = NewArray.sort();
  var SortNewArrayLength = SortNewArray.length;
  var prev = SortNewArray[0];
  var count = 1;
   for(var i =0; i<SortNewArrayLength; i++)
   {
     if(SortNewArray[i] == prev)
     {
         count++;
     }
    else
     {
         console.log(SortNewArray[i] + "  comes  " + count + "  times ");
         prev = SortNewArray[i];
         count = 1;
     }
  }

这是我得到的输出

enter image description here

无论我用红色标记。我希望这些按升序排列

请有人帮帮我吗?

2 个答案:

答案 0 :(得分:1)

var NewArray = [1,4,5,2,1,3,4,2,4,5,6,4,2,1,7];
var counts = {};

// first collect the count of each number
NewArray.forEach( function(n){
   if( counts[n] ){
        counts[n] += 1;   
   }
   else {
        counts[n] = 1;     
   }
});
// now counts = { 1:3, 2:3, 3:1, 4:4, 5:2, 6:1, 7:1 }

// get the keys (unique numbers from NewArray) and sort them by their values (count)
var keys = Object.keys( counts ).sort( function(a, b){
  return counts[a] > counts[b];  
})

// print key:value pairs sorted by value
keys.forEach( function( n ){
  console.log("%s comes %d times", n, counts[n] );  
})

/*
3 comes 1 times
6 comes 1 times
7 comes 1 times
5 comes 2 times
1 comes 3 times
2 comes 3 times
4 comes 4 times
*/

http://jsfiddle.net/s384qq66/

答案 1 :(得分:0)

var count = 1;更改为var count = 0;并更改

console.log(SortNewArray[i] + "  comes  " + count + "  times ");

console.log(SortNewArray[i-1] + "  comes  " + count + "  times ");