I have very simple question, i am learning javascript.
I have this 2D array :-
let text = [[1,a],[2,b]]
And I want to sum the numeric values of array, I know how to do it using for loop but is there any way to do in shorter way like we can do it using 1D array by using reduce
?
If i have this array :-
let text = [1,2]
I can easily sum it in one line like this :-
text.reduce((a,b) => a b)
Is there any way to do same way with 2d array too which also has string values.
Thanks
CodePudding user response:
You may use that same Array.prototype.reduce()
slightly modified:
const src = [[1,'a'],[2,'b']]
const sumByCol = (arr, col) =>
arr.reduce((acc, row) => acc =row[col], 0)
console.log(sumByCol(src,0))
CodePudding user response:
You could do the following
let text = [[1,'a'],[2,'b']]
let numbers_only = text.flat().filter(x => Number(x))
let sum = numbers_only.reduce((a,b) => a b)
//answer = 3
As a one-liner -
let sum = text.flat().filter(x => Number(x)).reduce((a,b) => a b)
CodePudding user response:
Assuming your inner arrays can contain a variable number of numbers/strings, you can use two .reduce()
calls. The inner .reduce()
call runs .reduce()
to sum the numeric values on each inner array. This works the same way that your .reduce()
method works that you shared, except that it only adds the current value to the sum
if its a number. The outer .reduce()
call is used to sum each inner array sum together into a final total result:
const text = [[1, 'a'],[2, 'b']];
const res = text.reduce((total, inner) =>
total inner.reduce((sum, val) => typeof val === "number" ? sum val : sum, 0)
, 0);
console.log(res);