array = ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue']
...我想要实现的输出会导致
output = ['blue x3', 'red x2', 'green x2', 'black']
我很难找到最有效的方法。
谢谢!
答案 0 :(得分: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"]
答案 1 :(得分: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]);
}
答案 2 :(得分: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(或更低版本)中不起作用。
答案 3 :(得分: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);