我使用map从多维数组中获取数组。以下是我的代码
var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
{"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
{"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.map(function(arr, count) {
return arr.points;
});
输出为[36,122,25]。 但我需要总和为183?
答案 0 :(得分:2)
使用Array#reduce
方法获取属性的总和。
var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
{"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
{"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.reduce(function(tot, arr) {
// return the sum with previous value
return tot + arr.points;
// set initial value as 0
},0);
console.log(result);
答案 1 :(得分:1)
只需在原始代码后面写下以下代码
var result = result.reduce(add, 0);
function add(a, b) {
return a + b;
}
console.log(result);
答案 2 :(得分:1)
使用数组' reduce()
,如下所示:
var data = [{"name":"ramu","id":"719","gmail":"ramu@gmail.com","ph":988989898,"points":36},
{"name":"ravi","id":"445","gmail":"ravi@gmail.com","ph":4554545454,"points":122},
{"name":"karthik","id":"866","gmail":"karthik@gmail.com","ph":2332233232,"points":25}]
var result = data.reduce(function(sum, item){
return sum = sum+item.points;
},0);
console.log(result);