• Jobs
  • About Us
  • Jobs
    • Home
    • Jobs
    • Courses and challenges
  • Businesses
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

129
Views
SUM certain column in an array (Javscript)

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

over 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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))

over 3 years ago · Juan Pablo Isaza Report

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)
over 3 years ago · Juan Pablo Isaza Report

0

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)
)

over 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Show me some job opportunities
There's an error!