-1
array = ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue']

...我试图实现的输出将导致

output = ['blue x3', 'red x2', 'green x2', 'black']

我很难找出最有效的方法来做到这一点。

谢谢!

4

4 回答 4

2
 var array = ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue'] 

 var hash = {};
 for( var i = 0; i < array.length; ++i){
     hash[array[i]] = (!hash.hasOwnProperty(array[i]) ? 1 : hash[array[i]]+1);
 }

 var output = [];
 for(var key in hash){
     output.push( key + (hash[key]>1 ? (" x"+hash[key]):"") );
 }
 console.log( output ); //["blue x3", "red x2", "green x2", "black"]

演示

于 2012-05-17T18:37:58.753 回答
0
var arr =  ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue'];

var group = {};
for (var i = arr.length; --i >= 0;) {
  var value = arr[i];
  group[value] = 1 - -(group[value] | 0);
}
var result = [];
for (e in group) { 
  result.push(e + ' x' + group[e]);
}
于 2012-05-17T18:36:21.143 回答
0

这是我很快想出的一个俗气的解决方案;

var array = ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue'],
    output = [], temp = {}, i;

// loop through array and count the values
array.forEach(function(a){
    temp[a] = temp[a] ? temp[a]+1 : 1;
});

// loop though temp and add "xN" to the values
for(i in temp){
    output.push(i + (temp[i] > 1 ? ' x'+temp[i] : ''));
}

console.log(output);

注意:.forEach在 IE 8(或更低版本)中不起作用。

于 2012-05-17T18:36:31.687 回答
0
// You can use an object to group strings
var colourGroups = {};
var array = ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue'];

// loop and group each colour. 
array.forEach(function(colourName) {

    if (colourGroups[colourName] )
        // increment the count
        colourGroups[colourName]++;
    else
        //initialize the property with 1
        colourGroups[colourName] = 1;

});    


// display results
var results = [];

for(var prop in colourGroups) {
    var colourCountStats = prop + " x " + colourGroups[prop];
    results.push(colourCountStats );
}

console.log(results);
document.write(results);​

JS 小提琴示例:http: //jsfiddle.net/peterf/J7EUc/

于 2012-05-17T18:55:42.960 回答