简体   繁体   中英

How to count a javascript array and get output like this?

i have a array like this

["5763.34", "5500.00", "5541.67", "5541.67"]

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)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM