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
You may use that same Array.prototype.reduce()
slightly modified to build up a custom summarizing function that may accept source array and col
variable indicating target column:
const src = [[1,'a'],[2,'b']]
const sumByCol = (arr, col) =>
arr.reduce((acc, row) => acc + row[col], 0)
console.log(sumByCol(src,0))
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)
You can achieve it in a single line by doing this :
let text = [[1,'a'],[2,'b']]
console.log(
text.flat()
.filter((item) => typeof item === 'number')
.reduce((total, item) => total + item)
)