0

I want to take all sub-arrays in a nested array, making a new array out of each depth (including the original input array), and place them into a new array.

Input:

var array = ["cat", ["dog", ["rabbit"]], "hamster"]

Output:

newArray = [
             ["cat", ["dog", ["rabbit"]], "hamster"], 
             ["dog", ["rabbit"]], 
             ["rabbit"]
           ]

Attempt:

var unnest = function(array) {
  var container = [array];
    for (var i in array) {
        if (array[i] instanceof Array) {
          container.push(array[i]);
        }
    }
  return container
}

I know this needs some sort of iterative or recursive process, but that's where I'm stuck (I'm new to JavaScript). Thanks.

2
  • 1
    So what have you tried then? Commented Jun 2, 2015 at 4:32
  • @Oka sorry, just added my attempted solution. Commented Jun 2, 2015 at 4:33

3 Answers 3

1

Here's a recursive implementation.

var unNest = function(array) {
  // Create a results array to store your new array
  var resultsArr = [];
  // Recursive function that accepts an array
  var recurse = function(array) {
    // Push the passed-in array to our results array
    resultsArr.push(array);
    // Iterate over the passed-in array
    for (var i = 0; i < array.length; i++) {
      // If an element of this array happens to also be an array,
      if (Array.isArray(array[i])) {
        // Run the recursive function, passing in that specific element which happens to be an array
        recurse(array[i]);
      }
    }
  }
  // Invoke our recurse function, passing in the original array that unNest takes in
  recurse(array);
  // Return the results array
  return resultsArr;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ah this is very clear. Thank you for the comments in your code. This helps a huge deal.
Glad you found it helpful!
0

You're close! There's only one thing you need to change: wrap your for loop in a function, so you can call it recursively. Here's one way of doing that.

var unnest = function(array) {
  var container = [array];

  var collectNestedArrays = function(array) {
    array.forEach(function(x) {
      if (x instanceof Array) {
        container.push(x);
        collectNestedArrays(x);
      }
    });
  };

  collectNestedArrays(array);

  return container;
};

1 Comment

Thank you, @troyastorino. I hit a wall when it came to the recursive part, but this helps much.
0

Because we iterate an array and create elements for parent array and each child array in the tree, This is a problem tat is best solve with a recursive DFS algorithm.

function unnest(src) {
  // overload the parameters and take the target array as a second argument.
  // this helps us avoid having nested functions, improve performance 
  // and reduce boilerplate
  var target = arguments[1] || [];

  // add the current array to the target array
  target.push(src);

  // iterate on the parent array and recursively call our function, 
  // assigning the child array, and the target array as function parameters
  src.forEach(function (node) {
    if (node instanceof Array) {
      unnest(node, target);
    }
  });
  return target;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.