如何对JavaScript数组对象形式的特定搜索ID中的值求和?

时间:2019-03-07 08:15:39

标签: javascript

我有如下所示的javascript数组对象。我需要基于数组对象中的seach id求和。

var array = [
{ id: 1, val: 10 }, 
{ id: 2, val: 25 }, 
{ id: 3, val: 20 }, 
{ id: 1, val: 30 }, 
{ id: 1, val: 25 }, 
{ id: 2, val: 10 }, 
{ id: 1, val: 20 }
],

例如,id 1的值之和是10 + 30 + 25 + 20 = 85,可能是链接linq,但我不确定在javascript中。感谢您提供所有答案。

9 个答案:

答案 0 :(得分:3)

您可以结合使用filter和reduce以获得所需的结果:

sumOfId = (id) => array.filter(i => i.id === id).reduce((a, b) => a + b.val, 0);

用法:

const sumOf1 = sumOfId(1); //85

阅读材料:

Array.prototype.filter

Array.prototype.reduce

答案 1 :(得分:1)

一种使用传统的for循环的方式

var array = [
  { id: 1, val: 10 }, 
  { id: 2, val: 25 }, 
  { id: 3, val: 20 }, 
  { id: 1, val: 30 }, 
  { id: 1, val: 25 }, 
  { id: 2, val: 10 }, 
  { id: 1, val: 20 }
];

var sums = {};
for (var i = 0; i < array.length; i++) {
  var obj = array[i];
  sums[obj.id] = sums[obj.id] === undefined ? 0 : sums[obj.id];
  sums[obj.id] += parseInt(obj.val);
}

console.log(sums);

running example

答案 2 :(得分:1)

JS 菜鸟在这里......我想像这样的东西也应该在这里:-)

let newArray = {}
array.forEach((e) => {
    !newArray[e.id] && (newArray[e.id] = 0);
    newArray[e.id] += e.val;
  });

答案 3 :(得分:0)

您可以使用reduce()findIndex()

var array = [
{ id: 1, val: 10 }, 
{ id: 2, val: 25 }, 
{ id: 3, val: 20 }, 
{ id: 1, val: 30 }, 
{ id: 1, val: 25 }, 
{ id: 2, val: 10 }, 
{ id: 1, val: 20 }
];
let res = array.reduce((ac,a) => {
  let ind = ac.findIndex(x => x.id === a.id);
  ind === -1 ? ac.push(a) : ac[ind].val += a.val;
  return ac;
},[])
console.log(res);

答案 4 :(得分:0)

reduce通过id淘汰1filtervar array = [{ id: 1, val: 10 }, { id: 2, val: 25 }, { id: 3, val: 20 }, { id: 1, val: 30 }, { id: 1, val: 25 }, { id: 2, val: 10 }, { id: 1, val: 20 } ]; var id = 1; var sum = array.filter(({ id }) => id == 1).reduce((acc, { val }) => acc + val, 0); console.log(sum);的所有项目:

var array = [{
    id: 1,
    val: 10
  },
  {
    id: 2,
    val: 25
  },
  {
    id: 3,
    val: 20
  },
  {
    id: 1,
    val: 30
  },
  {
    id: 1,
    val: 25
  },
  {
    id: 2,
    val: 10
  },
  {
    id: 1,
    val: 20
  }
];

var id = 1;
var sum = array.filter(function(i) { return i.id == 1}).reduce(function(acc, curr) { return acc + curr.val}, 0);

console.log(sum);

您是否需要ES5版本:

{{1}}

答案 5 :(得分:0)

您可以在数组上循环并检查ID。

var array = [
  { id: 1, val: 10 }, 
  { id: 2, val: 25 }, 
  { id: 3, val: 20 }, 
  { id: 1, val: 30 }, 
  { id: 1, val: 25 }, 
  { id: 2, val: 10 }, 
  { id: 1, val: 20 }
];

var sum = 0;
var id = 1;

$.each(array, function(index, object){
  if (object.id == id) {
    sum += object.val;
  }
});

console.log(sum);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

答案 6 :(得分:0)

您可以使用求和功能从GroupBy中提取linq.js

var array = [{ id: 1, val: 10 }, { id: 2, val: 25 }, { id: 3, val: 20 }, { id: 1, val: 30 }, { id: 1, val: 25 }, { id: 2, val: 10 }, { id: 1, val: 20 }],
    result = Enumerable
        .From(array)
        .GroupBy(null, null, "{ id: $.id, sum: $$.Sum('$.val') }", "$.id")
        .ToArray();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

答案 7 :(得分:0)

使用Array#reduceMap可以像这样获得每个ID的总和。这也使用destructuring来更快地访问属性。

const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];

const res = data.reduce((a,{id,val})=>{
  return a.set(id, (a.get(id)||0) + val);
}, new Map())

console.log(res.get(1));
console.log(res.get(2));

如果要输出所有总和,则需要使用Array#from

const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];

const res = Array.from(
  data.reduce((a,{id,val})=>{
    return a.set(id, (a.get(id)||0) + val);
  }, new Map())
);

console.log(res);

如果格式应与原始结构相似,则需要在其后添加Array#map进行转换。

const data=[{id:1,val:10},{id:2,val:25},{id:3,val:20},{id:1,val:30},{id:1,val:25},{id:2,val:10},{id:1,val:20}];

const res = Array.from(
  data.reduce((a,{id,val})=>{
    return a.set(id, (a.get(id)||0) + val);
  }, new Map())
).map(([id,sum])=>({id,sum}));

console.log(res);

答案 8 :(得分:0)

这里是另一个选择,引入了Array.prototype.sum助手:

Array.prototype.sum = function (init = 0, fn = obj => obj) {
    if (typeof init === 'function') {
        fn = init;
        init = 0;
    }

    return this.reduce(
        (acc, ...fnArgs) => acc + fn(...fnArgs), 
        init
    );
};

// .sum usage examples
console.log(
    // sum simple values
    [1, 2, 3].sum(),
    // sum simple values with initial value
    [1, 2, 3].sum(10),
    // sum objects
    [{ a: 1 }, { a: 2 }, { a: 3 }].sum(obj => obj.a),
    // sum objects with initial value
    [{ a: 1 }, { a: 2 }, { a: 3 }].sum(10, obj => obj.a),
    // sum custom combinations
    [{ amount: 1, price: 2 }, { amount: 3, price: 4 }]
        .sum(product => product.amount * product.price)
);

var array = [{ id: 1, val: 10 }, { id: 2, val: 25 }, { id: 3, val: 20 }, { id: 1, val: 30 }, { id: 1, val: 25 }, { id: 2, val: 10 }, { id: 1, val: 20 }];

// solutions
console.log(
    array.filter(obj => obj.id === 1).sum(obj => obj.val),
    array.filter(({id}) => id === 1).sum(({val}) => val),
    array.sum(({id, val}) => id === 1 ? val : 0)
);

引用: