array = ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue']
...我試圖達到的輸出會導致如何替換此數組中的倍數?
output = ['blue x3', 'red x2', 'green x2', 'black']
我有一個很難搞清楚這樣做的最有效途徑。
謝謝!
array = ['blue', 'red', 'green', 'green', 'red', 'blue', 'black', 'blue']
...我試圖達到的輸出會導致如何替換此數組中的倍數?
output = ['blue x3', 'red x2', 'green x2', 'black']
我有一個很難搞清楚這樣做的最有效途徑。
謝謝!
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"]
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]);
}
這是我很快提出的一個俗氣的解決方案;
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(或更低)工作。
// 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);
你嘗試什麼嗎?你在「最有效」的方式遇到麻煩或者根本無法工作?顯示你已經嘗試了什麼,或者人們可以發佈你正在使用的確切方法。 –
不要擔心最有效的方法,只是嘗試一些方法 – Ibu
是的,我試圖找到indexOf的第一個值,然後替換該值,但它沒有考慮多個值,除非我遞歸,並且看起來不像右邊方式,必須有更好的方法。 – fancy