[Solved] Javascript : Sum into array


Here is an object version. This is not really what you’re after, but along the same lines and honestly, a bit neater as it’s a data structure.

var myArray = [ "Apple: 10", "Apple: 3", "Banana: 3", "Pear: 7", "Pineapple: 7" ];
var newArray = {};

myArray.forEach(function(val) {
  var item =  val.split(":");
  var key = item[0];
  var num = parseInt(item[1], 10);

  if ( newArray.hasOwnProperty(key) ){
    newArray[key] += num;
  } else {
    newArray[key] = num;
  }

});

alert ( JSON.stringify(newArray) );

And, as said in the comments, when we look at:

myArray .push($(this).attr('id') + " : " +$(this).val());

And

myArray [ "Apple: 10", "Apple: 3", "Banana: 3", "Pear: 7", "Pineapple: 7" ]

You seem to have duplicate IDs in your document which needs to be fixed first as an ID must be unique in any given document.

0

solved Javascript : Sum into array