在一个数组中求和所有相同的元素

时间:2016-11-30 16:38:36

标签: javascript arrays

如何在一个数组中求和所有相同的元素?例如,我有一个数组:

  [20,20,20,10,10,5,1]

如何制作[60,20,5,1]

这是我到目前为止所尝试的内容:

var money = [20, 20, 20, 10, 10, 5, 1];
for (var i = 0; i < money.length; i++) {
  if (money[i] == money[i + 1]) {
    money[i] += money[i + 1];
    money.splice(money.indexOf(money[i + 1]), 1);
  }
}

5 个答案:

答案 0 :(得分:4)

我会做这样的事情:

  1. 计算出现次数。
  2. 将值乘以出现次数。
  3. <强>段

    &#13;
    &#13;
    // Our original array.
    var arr = [20, 20, 20, 10, 10, 5, 1];
    // Let's have a counts object that stores the counts.
    var counts = {};
    
    // Loop through the array to get the counts.
    for (var i = 0; i < arr.length; i++) {
      var num = arr[i];
      counts[num] = counts[num] ? counts[num] + 1 : 1;
    }
    
    // Have a final array.
    var fin = [];
    // Multiply the count with the values and push it to the final array.
    for (var count in counts) {
      fin.push(counts[count] * count);
    }
    
    console.log(fin);
    &#13;
    &#13;
    &#13;

答案 1 :(得分:2)

使用Array#reduce方法和变量存储前一个元素。

var arr = [20, 20, 20, 10, 10, 5, 1];
// variable for storing previous element
var prev;

var res = arr.reduce(function(arr, v) {
  // if element is same as previous then add 
  // value with last element
  if (prev == v)
    arr[arr.length - 1] += v;
  // else push and update prev variable
  else
    arr.push(prev = v)
    // return the array refernece
  return arr;
  // set initial value as empty array for result
}, [])

console.log(res);

UPDATE:如果相同的值不相邻,则使用对象引用索引。

var arr = [20, 20, 20, 10, 10, 5, 1];
// object for refering index
var ref = {};

var res = arr.reduce(function(arr, v) {
  // check property is defined or not if 
  // defined update value at the index
  if (ref.hasOwnProperty(v))
    arr[ref[v]] += v;
  else {
    // else add property to object and push element
    ref[v] = arr.length;
    arr.push(prev = v)
  }
  // return array reference
  return arr;
  // set initial value as empty array for result
}, [])

console.log(res);

答案 2 :(得分:1)

var list= [20,20,20,10,10,5,1];
var result=[];
//index of already added values
var listOfIndex=[];
for(var i=0;i<list.length;i++){ 
if(listOfIndex.indexOf(i)>=0){
   continue;
}
var number=list[i];
for(var j=i+1;j<list.length;j++){ 
if(list[i]==list[j]){       
   number = number+list[j];
   listOfIndex.push(j);//push in this list the index of the value that has been added
  }
 }
 result.push(number);
}
console.log(result);

答案 3 :(得分:0)

您可以使用哈希表并存储结果槽的索引。这也适用于未排序的值。

var data = [20, 20, 20, 10, 10, 5, 1],
    result = [];

data.forEach(function (a) {
    if (!(a in this)) {
        this[a] = result.push(0) - 1;
    }
    result[this[a]] += a;
}, Object.create(null));
 
console.log(result);

答案 4 :(得分:0)

使用Array.prototype.reducehash table存储索引的另一个单循环提议 - 正在创建的结果数组 - 将处理未排序的输入。

见下面的演示:

var array = [20, 20, 20, 10, 10, 5, 1];

var result = array.reduce(function(hash){
  return function(p,c) {
    if(c in hash) {
      p[hash[c]] += c;
    } else {
      // store indices in the array
      hash[c] = p.push(c) - 1;
    }
    return p;
  };
}(Object.create(null)),[]);

console.log(result);