Mojimi
Mojimi

Reputation: 3161

Flatten array to 2D

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?

Upvotes: 1

Views: 49

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

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; }

Upvotes: 3

Related Questions