1

I know there are a couple of answers on the matter, but as I was trying to make my own, I got very lost on how recursive functions work, here's what I tried :

function flatcoords(arr) {
  for (i = 0; i < arr.length; i++) {
    const value = arr[i];
    if (value.isArray) {
      return flatcoords(value);
    } else {
      return arr;
    }
  }

}

const arr_test = [
  [
    [1, 2],
    [1, 2]
  ],
  [1, 2],
  [1, 2],
  [
    [
      [1, 2],
      [1, 2]
    ]
  ]
];

//wanted_result = [ [1,2],[1,2],[1,2],[1,2],[1,2],[1,2] ]
console.log(flatcoords(arr_test));

I want the result to be a 2D array, what am I missing in my logic?

2
  • [1, 2][? shouldn't there be a comma after ]? Commented Dec 5, 2017 at 18:48
  • @gurvinder372 oops, fixed, thanks Commented Dec 5, 2017 at 18:49

1 Answer 1

3

First of all, you need to declare all variables before use. Then you could use Array.isArray for a check if an item is an array.

In this case, I suggest to check the first item of the checked element if it is an array as well, in this case flat the array.

As result, an array comes in handy, because not only one element should be returned, but all. And while arrays have more item, you need to append all items to the existing result array.

function flatcoords(array) {
    var result = [],
        value,
        i;

    for (i = 0; i < array.length; i++) {
        value = array[i];
        if (Array.isArray(value) && Array.isArray(value[0])) {
            result = result.concat(flatcoords(value));
        } else {
            result.push(value);
        }
    }
    return result;
}

const arr_test = [[[1, 2], [1, 2]], [1, 2], [1, 2], [[[1, 2], [1, 2]]]];

console.log(flatcoords(arr_test));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

2 Comments

What stops result from being reset to an empty array once you recursively call the function?
@CarlEdwards, at least, you get the elment or the inner array.

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.