Answer the question
In order to leave comments, you need to log in
Can this code be simplified?
Can this code be simplified to solve this problem?
Here is the code:
function sumsInArray(arr){
const newArr = [];
for (let i = 0; i < arr.length; i++){
let sum = 0;
if (arr[i].length === 0) newArr.push(sum);
for (let j = 0; j < arr[i].length; j++){
sum += arr[i][j];
if (j === arr[i].length - 1) {
newArr.push(sum);
sum = 0;
}
}
}
return newArr;
}
Answer the question
In order to leave comments, you need to log in
function sumsInArray(arr) {
return arr.map(innerArr => innerArr.reduce((a, b) => (a + b), 0));
}
It can be reduced, it is possible to win back a drop of time. But it's unlikely to be easy. In terms of making it clear to a person who is not good at JS)
Look here . And then to the left sidebar, there are a lot of interesting things that can shorten the record.
Here he simplified it into two lines for those who are interested) One nuance and minus two if lines )
unction sumsInArray(arr){
const arrNew = [];
let sum;
for (let i = 0; i < arr.length; i++) {
sum = 0;
for (let j = 0; j < arr[i].length; j++) {
sum = sum + arr[i][j];
}
arrNew.push(sum);
}
return arrNew;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question