Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterative solution for flattening n-th nested arrays in Javascript

Can anyone show me an iterative solution for the following problem? I solved it recursively but struggled with an iterative solution. (Facebook Technical Interview Question)

Input: [1, {a: 2}, [3], [[4, 5], 6], 7]
Output: [1, {a: 2}, 3, 4, 5, 6, 7]

Solution must work with n-th nested array elements (i.e. it must still work if someone modifies the array values/placement in the example above)

Recursive solution:

var flatten = function(input) {
    var result = [];

    input.forEach(function(element) {
        result = result.concat(Array.isArray(element) ? flatten(element) : element);
    });

    return result;
}
like image 558
subject117 Avatar asked May 01 '15 16:05

subject117


People also ask

How do you flatten nested arrays?

The array method accepts an optional parameter depth , which specifies how deep a nested array structure should be flattened (default to 1 ). So to flatten an array of arbitrary depth, just call flat method with Infinity .

Which method is used to convert nested arrays to objects in JavaScript?

toString() method is used to convert: an array of numbers, strings, mixed arrays, arrays of objects, and nested arrays into strings.


2 Answers

How about this?

inp = [1, {a: 2}, [3], [[4, 5], 6], 7]
out = inp;

while(out.some(Array.isArray))
  out = [].concat.apply([], out);

document.write(JSON.stringify(out));
like image 158
georg Avatar answered Nov 15 '22 21:11

georg


Here's a solution that flattens in place.

function flatten(arr) {
  var i = 0;

  if (!Array.isArray(arr)) {
    /* return non-array inputs immediately to avoid errors */
    return arr;
  }

  while (i < arr.length) { 
    if (Array.isArray(arr[i])) {
      arr.splice(i, 1, ...arr[i]);
    } else {
      i++;
    }
  }
  return arr;
}

This solution iterates through the array, flattening each element one level of nesting at a time until it cannot be flattened any more.

like image 21
Lope Avatar answered Nov 15 '22 20:11

Lope