How to make one -dimensional JavaScript out of a multidimensional array

Flatten multidimensional arrays in JavaScript using Array.reduce & Array.concat for a concise, efficient solution w/ example. §§ COM Flatten multidimensional arrays in JavaScript using Array.reduce & Array.concat for a concise, efficient solution w/ example.

Creating a One-Dimensional Array from a Multidimensional Array in JavaScript

Creating a one-dimensional array from a multidimensional array can be useful in many situations. It can be used to simplify complex data structures, or to create a flat list of items from a more complex structure. In JavaScript, this can be accomplished using the Array.prototype.flat() method, or by using a for loop to iterate through the elements.

The Array.prototype.flat() method will take a multidimensional array and return a new one-dimensional array with all of the elements of the original array. This method can be used to flatten an array up to a specified depth.


// Multidimensional array
let arr = [[1, 2], [3, 4], [5, 6]];

// Flatten the array up to 1 level
let oneDimensional = arr.flat(1);

console.log(oneDimensional); // [1, 2, 3, 4, 5, 6]

If the depth of the array is unknown, or you want to flatten all nested elements, you can use a for loop to iterate over the array and create a new array with all of the elements. This approach is not as efficient as using the Array.prototype.flat() method, but it is useful for more complex data structures.


// Multidimensional array
let arr = [[1, 2], [3, 4], [5, 6], [7, [8, 9]]];

// Create an empty array to store flattened elements
let oneDimensional = [];

// Iterate over the elements of the array
for (let i = 0; i < arr.length; i++) {
  // If the element is an array, flatten it recursively
  if (Array.isArray(arr[i])) {
    let flattened = flattenArray(arr[i]);
    // Add flattened elements to the oneDimensional array
    oneDimensional = oneDimensional.concat(flattened);
  } else {
    // If the element is not an array, add it to the oneDimensional array
    oneDimensional.push(arr[i]);
  }
}

console.log(oneDimensional); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Recursive function to flatten nested arrays
function flattenArray(arr) {
  let oneDimensional = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      let flattened = flattenArray(arr[i]);
      oneDimensional = oneDimensional.concat(flattened);
    } else {
      oneDimensional.push(arr[i]);
    }
  }
  return oneDimensional;
}

Both of these approaches can be used to create a one-dimensional array from a multidimensional array in JavaScript. Using the Array.prototype.flat() method is more efficient, but the for loop approach can be more flexible for more complex data structures.

Answers (0)