0

I need help flattening an array like this:

[1,2,[2,3],[5,[6,1],4],7]

I want it to be something like

[1,2,2,3,5,6,1,4,7].

I have searched something like this, and found [].concat.apply, but it will only take care of the two dimensional arrays.

I also want to use an algorithm that will work for any jagged multi dimensional arrays. Please help. Thx

user94559
  • 59,196
  • 6
  • 103
  • 103
nova_n
  • 23
  • 7

2 Answers2

1

My recommendation would be to take a dependency on lodash and use the flattenDeep function.

_.flattenDeep([1,2,[2,3],[5,[6,1],4],7])
// [ 1, 2, 2, 3, 5, 6, 1, 4, 7 ]

If you want to write your own function, you might want to peek at the lodash implementation.

In pseudo-code, here's a recursive approach:

result = []
function flatten(array)
  for each element in array
    if element is array
      flatten(element)
    else
      result.append(element)

EDIT

Here's a "by-hand" approach, though I'd definitely recommend relying on the better-tested lodash implementation.

function flatten(arr, result) {
  if (result === undefined) {
    result = [];
  }

  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      flatten(arr[i], result);
    } else {
      result.push(arr[i]);
    }
  }

  return result;
}

console.log(flatten([1, 2, [2, 3], [5, [6, 1], 4], 7]));

// Output:
// [ 1, 2, 2, 3, 5, 6, 1, 4, 7 ]
user94559
  • 59,196
  • 6
  • 103
  • 103
  • thx, but this question relates to a problem on a website. i can only solve it with vanilla javascript – nova_n Jul 31 '16 at 17:34
  • @nova_n Why can't you use lodash? – user94559 Jul 31 '16 at 17:35
  • Just add `` to the `` section of your HTML. – user94559 Jul 31 '16 at 17:36
  • This site only allows vanila javascript for training. – nova_n Jul 31 '16 at 17:42
  • Thanx for the by hand solution tho – nova_n Jul 31 '16 at 17:42
  • @nova_n: You should really make _some_ attempt to solve these codewars questions on your own. You will learn much more by looking for a solution, experimenting with some code to see what happens, tracing through your code in the JavaScript debugger, and studying the language in more depth. Asking for someone to write out the solution for you may get you through the codewars tests, but you won't learn nearly as much that way. – Michael Geary Jul 31 '16 at 23:26
  • i know. this was only part of a question. i wanted to flatten an array so i could itterate thru values in deeply nested arrays. The project was about counting strings in objects. some of the properties were objects, arrays, and strings – nova_n Aug 08 '16 at 02:08
1

You can wrap the concat.apply thing in a loop to handle deeply nested arrays:

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

or in the ES6 syntax:

while (a.some(Array.isArray)) 
    a = [].concat(...a);
georg
  • 211,518
  • 52
  • 313
  • 390