Javascript:汇总到数组

时间:2015-04-28 12:31:52

标签: javascript jquery object sum

我的功能是:

var myArray = new Array();
$('input:checked').each(function(index) {
    myArray .push($(this).attr('id') + " : " +$(this).val());
});

让我知道如何在这个数组中求和:

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

我的结果>

myNewArray [ "Apple: 13",  "Banana: 3", "Pear: 7", "Pineapple: 7" ]

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

这是一个对象版本。这不是你真正想要的,但是在同一条线上,诚实地说,它有点整洁,因为它是一个数据结构。

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

而且,正如评论中所说,当我们看到:

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

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

您的文档中似乎有重复的ID需要先修复,因为ID在任何给定的文档中必须是唯一的。

答案 1 :(得分:0)

使用正则表达式拆分数组元素并将它们添加到临时对象:

var regex = /([A-Za-z]+): (\d+)/
var obj = {};
for (var i = 0, l = arr.length; i < l; i++) {
  var match = arr[i].match(regex);
  var name = match[1];
  var value = match[2];
  if (!obj[name]) obj[name] = 0;
  obj[name] += +value;
}

这将为您留下一个看起来像这样的对象:

console.log(obj) // { Apple: 13, Banana: 3, Pear: 7, Pineapple: 7 }

我个人会这样离开它,因为对象真的很容易操作。

但是,如果你真的需要数据再次返回数组,只需遍历对象并将字符串作为元素推送到数组中:

var out = [];
for (var p in obj) {
    out.push(p + ': ' + obj[p]);
}

console.log(out) // [ "Apple: 13", "Banana: 3", "Pear: 7", "Pineapple: 7" ]

DEMO

答案 2 :(得分:-1)

尝试这样的事情。

&#13;
&#13;
var data =  [ "Apple: 10", "Apple: 3", "Banana: 3", "Pear: 7", "Pineapple: 7" ];
var newObject = {};
var sum = 0;
$.each(data,function(k,v){
  var key = v.split(":")[0];
  var value = v.split(":")[1];
  if((key in newObject))
  {
    newObject[key] = parseInt(newObject[key]) + parseInt(value);
  }
  else
  {
    newObject[key] = $.trim(value);
  }
  
});
console.log(newObject);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:-2)

以前的回答是错误的。 我已经修好了,抱歉

var myArray = [ "Apple: 10", "Apple: 3", "Banana: 3", "Pear: 7", "Pineapple: 7" ],
newArray= {},
i,
temp;
for (i=0; i<myArray.length;i++){
     temp = myArray[i].split(':');
     temp[0] = temp[0].replace( /\s/g, "");
     temp[1] = temp[1].replace( /\s/g, "");
    if(newArray[temp[0]]){
         newArray[temp[0]] = newArray[temp[0]] + parseInt(temp[1]);
    }else{
          newArray[temp[0]] = parseInt(temp[1]);
    }
 }
 console.log(newArray);