How to count a javascript array and get output like this?
i have a array like this
["5763.34", "5500.00", "5541.67", "5541.6开发者_运维百科7"]
i want to count similar values and get a out put like
(1 * 5763.34) + (1 * 5500.00) + (2 * 5541.67)
any idea how to do this?
Count values:
var array = ["5763.34", "5500.00", "5541.67", "5541.67"]
var counts = {};
for (var i = 0; i < array.length; ++i) {
var val = array[i];
if (val in counts) {
counts[val]++;
} else {
counts[val] = 1;
}
}
Print them:
var strings = [];
for (var k in counts) {
strings.push('(' + counts[k] + ' * ' + k + ')');
}
alert(strings.join(' + '));
Try it here: http://jsfiddle.net/k46kL/1
do it like this
sum = 0
for(i=0; i< array.length; i++){
sum += array[i] * (i+1)
}
精彩评论