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))
CodePudding user response:
You could use map
and reduce
to achieve this as well.
const arr = [
['-', 2, 21],
[1, '-', 4, 54],
[5, 2, 2],
[11, 5, 3, 1],
];
const sums = arr.map((sub) =>
sub.reduce((previous, current) => {
// check here that the value is a number
if (typeof current === 'number') {
return previous current;
}
return previous;
}, 0)
);
console.log(sums);
// returns [23, 59, 9, 20]
CodePudding user response:
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)
CodePudding user response:
Using splice() would help remove the - from the array