A
A
Aliaksandr Chapkouski2020-04-19 04:14:31
JavaScript
Aliaksandr Chapkouski, 2020-04-19 04:14:31

Can this code be simplified?

Can this code be simplified to solve this problem?
5e9ba58094346017256083.png
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

3 answer(s)
I
Ivan Klimenko, 2020-04-19
@Sanchous2508

function sumsInArray(arr) {
    return arr.map(innerArr => innerArr.reduce((a, b) => (a + b), 0));
}

A
Arseny, 2020-04-19
Matytsyn @ArsenyMatytsyn

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.

A
Aliaksandr Chapkouski, 2020-04-19
@Sanchous2508

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 question

Ask a Question

731 491 924 answers to any question