Sum Of Same Nested Array Data Using Jquery
sample data array_data = [ [6326586, 0.4126], [6326586, 0.48], [6326586, 0.45], [6326586, 0.35], [6326586, 0.2685], [6326614, 0.4008], [6326614, 0.1], [6326614, 0.
Solution 1:
Using Map
and Array#Reduce
in Vanilla JS
const
arr = [[6326586,.4126],[6326586,.48],[6326586,.45],[6326586,.35],[6326586,.2685],[6326614,.4008],[6326614,.1],[6326614,.074],[6327407,.066],[6327408,.1],[6344999,.1572],[6344999,.003],[6394500,.2112]],
res = Array.from(arr.reduce((m, [k, v]) => m.set(k, (m.get(k) || 0) + v), new Map()))
console.log(res)
Using Object
and Array#Reduce
in Vanilla JS
** Go through the comments before using this
const
arr = [[6326586,.4126],[6326586,.48],[6326586,.45],[6326586,.35],[6326586,.2685],[6326614,.4008],[6326614,.1],[6326614,.074],[6327407,.066],[6327408,.1],[6344999,.1572],[6344999,.003],[6394500,.2112]],
res = Object.values(arr.reduce((o, [k, v]) => (o[k] ??= [k, 0], o[k][1] += v, o), {}));
console.log(res)
Solution 2:
You can do this in plain JavaScript, you don't need jQuery. You can use Array.reduce
as follows:
const array_data = [
[6326586, 0.4126],
[6326586, 0.48],
[6326586, 0.45],
[6326586, 0.35],
[6326586, 0.2685],
[6326614, 0.4008],
[6326614, 0.1],
[6326614, 0.074],
[6327407, 0.066],
[6327408, 0.1],
[6344999, 0.1572],
[6344999, 0.003],
[6394500, 0.2112]
]
const result = array_data.reduce((acc, [key, value]) => {
if (acc[key]) {
acc[key][1] += value;
} else {
acc[key] = [key, 0];
}
return acc;
}, {});
console.log(Object.values(result));
Post a Comment for "Sum Of Same Nested Array Data Using Jquery"