DEV Community

Shirley
Shirley

Posted on • Edited on

Flattening a Multidimensional array and Summing up a multidimensional array

I've encountered problems with multidimensional arrays and you need to use recursion to solve the problem. Here are two examples of such problems.

  1. The first problem is summing the elements of the array, given a multidimensional array. For example, given
let arr = [1,[1,2,[3,4]]]
Enter fullscreen mode Exit fullscreen mode

The sum would be 11.
Here is my code using recursion to solve the problem:

function sumArrays(arr) {
  let sum = 0;
  for (let i = 0; i < arr.length; i++) {
    if(Array.isArray(arr[i])){
      sum += sumArrays(arr[i]);
    } else {
      sum += arr[i];
    }
  }
  return sum;
}
Enter fullscreen mode Exit fullscreen mode

First, instantiate a variable sum. Then loop through the array. Check whether arr[i] is an array using Array.isArray. If it is an array, call the function sumArrays on the element again and add the sum to the sum variable. If the element is not an array, simply add the element to the sum.
For example, the first element 1 is not an array so add 1 to sum, so sum is now 1. The second element [1,2,[3,4]] is an array, so call sumArrays on it. It will loop through the element and check each element in the array. 1, 2 are elements so add that to sum. [3,4] is array so loop through that again and add the elements to the sum.

  1. The second example is using recursion to flatten a multidimensional array. You want a one dimensional array of all the elements in the multidimensional array. For example given
[1, [1, 2, [3, 4]]]
Enter fullscreen mode Exit fullscreen mode

you want

[1,1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Here's my code:

function flattenArray(arr) {
  return arr.reduce((acc, ele) => {
    return acc.concat(Array.isArray(ele) ? flattenArray(ele) : ele)
  }, [])
}
Enter fullscreen mode Exit fullscreen mode

Here I'm using the reduce function to concat the elements of the array to the accumulator variable which starts as an empty array. In my reduce function, I concat the element to the accumlator array. I check whether the element is an array, if so, I call the function flattenArray on it recursively. If not, I just concat the element to the array.

I hope this clears up any confusion regarding recursion in multidimensional arrays. Hope this helped.

Top comments (0)