Skip to content

Instantly share code, notes, and snippets.

@hiyangguo
Last active December 8, 2016 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiyangguo/79443797e5ed01f2b6cb2ec7087a404c to your computer and use it in GitHub Desktop.
Save hiyangguo/79443797e5ed01f2b6cb2ec7087a404c to your computer and use it in GitHub Desktop.
数组求和
/**
* Created by Godfery on 2016/12/8.
*/
/**
* Created by Godfery on 2016/12/7.
*/
var a = [['bj', 1, 'sh', 2, 'wh', 3], ['gz', 4, 'bj', 5], ['sh', 6], ['sh', 5]];
/**
* 获取数组聚合
* @param array
* @return {*}
*/
function getAggregation(array) {
var key, value;
return array.reduce(function (all, map, index) {
map.forEach(function (key, i) {
if (i % 2 === 0) {
value = map[i + 1];
all.push([key, value]);
}
});
return all;
}, []).reduce(function (count, arr) {
key = arr[0];
value = arr[1];
if (!count[key]) {
count[key] = 0;
}
count[key] += value;
return count;
}, {});
}
getAggregation(a);
/**
* 获取求和数组
* @param arrays
* @return {Array}
*/
function getCountArray(arrays) {
arrays = arrays.reduce(function (strs, array) {
strs.push(array.join(','));
return strs;
}, []).join(',').split(',');
var countMap = arrays.reduce(function (count, arr, i) {
if (i % 2 === 0) {
var key = arrays[i],
value = +arrays[i + 1];
if (!count[key]) {
count[key] = 0;
}
count[key] += value;
}
return count;
}, {});
return Object.keys(countMap).map(function (key) {
return [key, countMap[key]];
});
}
getCountArray(a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment