I have 2D array like this :
[[ONE,1],[QUARTER,0.25],[QUARTER,0.25]]
I want it to become :
[[ONE,1],[QUARTER,0.5]]
I tried using array.IndexOf but no luck
ONE,1,QUARTER,0.25,QUARTER,0.25
Contrary to your question title, your example suggests you want sum , as opposed to filter, the array.
let arr = [['ONE', 1], ['QUARTER', 0.25], ['QUARTER', 0.25]]; let sums = arr.reduce((sums, item) => { let found = sums.find(([key]) => key === item[0]); if (found) found[1] += item[1]; else sums.push(item); return sums; }, []); console.log(sums);
You could reduce the array by looking if the same key exists.
var array = [['ONE', 1], ['QUARTER', 0.25], ['QUARTER', 0.25]], result = array.reduce((r, [key, value]) => { var temp = r.find(a => a[0] === key); if (temp) { temp[1] += value; } else { r.push([key, value]); } return r; }, []); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.