Convert 2D nested array into 1D array in JavaScript?

Given a 2D array as shown in the example, how to manage to combine the string digits into one.

ex: Array2 = [[1,2,3],[4,5,6],[7,8,9]];

required sol:

Array1 = [123, 245, 789];

Answer

You can deconstruct your task into two separate problems, that we will solve in turn.

  1. We need to take an array of numbers (e.g. [1, 2 ,3]) and join them together into a string (e.g. ‘123’).

There is, in fact, a dedicated function for this in JavaScript – the join() function:

[1, 2, 3].join(''); // '123'
  1. We need to perform the previous function on each object in an array, returning an array of the transformed objects.

JavaScript again has you covered, this time with the map() function:

[a, b, c].map((element) => foo(element)); // [foo(a), foo(b), foo(c)]

All we have to do now is join these too together, so that the operation we perform on each element of the parent array, is to join all of the child elements together:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]].map((array) => array.join('')); // ['123', '456', '789']

Leave a Reply

Your email address will not be published. Required fields are marked *