2

There is such an arbitrary array in which I need to find the sum of all numbers without using Array.isArray:

let arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]]; 

The solution should look something like this:

let arr = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]; 

for (let i = 0; i < arr.length; i++) { 
   for (let j = 0; j < arr[i].length; j++) { 
      console.log(arr[i][j]);
   }
}

Could you please advise me on how to achieve this?

4
  • can you flatten the array and simply use for loop to calculate the sum ? Commented Sep 12, 2020 at 8:27
  • what about other array methods? Commented Sep 12, 2020 at 8:31
  • 1
    This requires some form of recursion or stack that can handle “N” nesting levels, at some level - the solution concept shown will fail on the input within 3 levels of nesting. It will also need some method to determine if an element is an array (or is not a number), even if it’s not “isArray”. Commented Sep 12, 2020 at 8:37
  • check this Commented Sep 12, 2020 at 8:40

3 Answers 3

1

Solution

Use flat and reduce methods to accomplish this.

Example

let arr = [[1, 2, 
3, [4, 5, [6, 7]]], 
[8, [9, 10]]];

arr.flat(Infinity).reduce((a, b) => a + b, 0)

References

Flat: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

Reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Sign up to request clarification or add additional context in comments.

1 Comment

This is giving a wrong output. I think you need to pass Infinity as an argument to flat()
1

You could take Array#flat and Array#reduce the array or check the instance of the given value with instanceof operator.

function getSum1(array) {
    return array.flat(Infinity).reduce((sum, value) => sum + value, 0);
}

function getSum2(array) {
    let sum = 0;
    for (const value of array) {
        sum += value instanceof Array
            ? getSum2(value)
            : value
    }
    return sum;
}

let array = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];

console.log(getSum1(array));
console.log(getSum2(array));

Comments

-1

you use lodash for this:

var _ = require("lodash");
var arr = [[1, 2, 3, [4, 5, [6, 7]]], [8, [9, 10]]];
flatArr = _.flattenDeep(arr);
flatArr.reduce((sum, value) => sum + value, 0);

3 Comments

what was the issue for giving -1?
Possibly because the additional dependency is unnecessary.
I have provided an alternative solution. Which was not mentioned above

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.