0

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?

1
  • Is your question more about the general method/algorithm, or more about the javascript implementation? Commented Sep 7, 2011 at 10:44

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

do it like this

sum = 0
for(i=0; i< array.length; i++){
    sum += array[i] * (i+1)
 }

2 Comments

may be i got your question wrong? do you want to sum them all or what?
not sum them all just to show the how calculation is done. expected answer is provided above by arnaud576875 Thanks for reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.