Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove '-' from the array number elements run through this function in JS?

I’m using this function below to sum "columns" of a 2D Array, but some elements contain '-' and I haven’t been able to handle it:

I’ve tried Number(num) or typeof num === 'number', but still…

const arr = [
   ['-', 2, 21],
   [1, '-', 4, 54],
   [5, 2, 2],
   [11, 5, 3, 1]
];

 const sumArray = (array) => {
   const newArray = [];
   array.forEach(sub => {
      sub.forEach((num, index) => {
         if(newArray[index]){
            newArray[index] += num;
         }else{
            newArray[index] = num;
         }
      });
   });
   return newArray;
}
console.log(sumArray(arr))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try:

const arr = [
  ['-', 2, 21],
  [1, '-', 4, 54],
  [5, 2, 2],
  [11, 5, 3, 1]
];

const sumArray = (array) => {
  const newArray = [];
  array.forEach(sub => {
    sub.forEach((num, index) => {
      if (typeof num == 'number') {
        if (newArray[index]) {
          newArray[index] += num;
        } else {
          newArray[index] = num;
        }
      }
    });
  });
  return newArray;
}
console.log(sumArray(arr))

Here’s a more concise solution:

const arr = [
  ['-', 2, 21],
  [1, '-', 4, 54],
  [5, 2, 2],
  [11, 5, 3, 1]
];

const result = arr.map((e, i) => arr.reduce((a, c) => (typeof c[i] == 'number' ? a + c[i] : a), 0))
console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading