stacked arrays

Asked

Viewed 45 times

4

I gave a search through the internet and did not find answer for this my problem. Imagine that you have arrays stacked. For example:

var array = [[[1, 2], [3, 4]], [[[5, 6], [7, 8]], [9, 10]]];

What I would like to do is take the smallest possible arrays and sort them within just one array. So:

array = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];

Can you help me?

1 answer

5


You can create a method that goes through your items array and:

  • If you find an element, add the array of origin to the result;
  • If you find a array, Scroll this to see if you have others arrays or elements of another type.

const array = [[[1, 2], [3, 4]], [[[5, 6], [7, 8]], [9, 10]]];

const percorrer = (item, resultado = []) => {
  for (const subitem of item) {
    if (Array.isArray(subitem)) {
      percorrer(subitem, resultado);
    } else {
      resultado.push(item);
      break;
    }
  }

  return resultado;
};

console.log(JSON.stringify(percorrer(array)));

You can also use the function reduce to generate the array by checking the type of the array:

const array = [[[1, 2], [3, 4]], [[[5, 6], [7, 8]], [9, 10]]];

// Checa se é um array de arrays
const checar = (array) => array.reduce((acumulador, item) => Array.isArray(item) ? acumulador : false, true);

const reducer = (acumulador, item) => checar(item) ? acumulador.concat(amassar(item)) : acumulador.concat([item]);

const amassar = (origem) => origem.reduce(reducer, []);

console.log(amassar(array));

reduce

The method reduce() performs a function reducer (provided by you) for each member of the array, resulting in a single return value.

Example:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Browser other questions tagged

You are not signed in. Login or sign up in order to post.