How to flatten array in JavaScript? [SOLVED]


JavaScript

Introduction

Arrays in JavaScript can contain other arrays, which can contain yet more arrays, and so on. This can lead to a nested structure of arrays that can be difficult to work with. Flattening an array means reducing the array to a single level, so that all the elements are contained directly within the top-level array, rather than being nested within other arrays.

There are a few different ways to flatten an array in JavaScript, depending on your needs and the structure of the array you are working with. Here are three common approaches:

 

Method-1: Using the concat() method

One way to flatten an array is to use the concat() method, which concatenates (joins) the elements of one or more arrays and returns a new array. You can use this method to flatten an array by iterating through the array and concatenating each element with the flattened array.

Here's an example of how you could use concat() to flatten an array:

function flattenArray(arr) {
    let flattened = [];
    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            flattened = flattened.concat(flattenArray(arr[i]));
        } else {
            flattened.push(arr[i]);
        }
    }
    return flattened;
}

const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray);

Output

[ 1, 2, 3, 4, 5, 6 ]

In this example, we have a function called flattenArray() that takes an array as an argument. The function uses a for loop to iterate through the elements of the array. If the current element is an array, it calls itself recursively to flatten that array and then concatenates the result with the flattened array. If the current element is not an array, it simply pushes the element onto the flattened array.

This approach works well for shallow arrays, but it can be inefficient for arrays with many levels of nesting since it requires multiple iterations through the array.

 

Method-2: Using the flat() method

Starting with ECMAScript 2019 (ES10), JavaScript has a built-in method called flat() that can be used to flatten an array. This method creates a new, one-dimensional array that includes all the elements of the original array, and any nested arrays.

Here's an example of how you could use flat() to flatten an array:

const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = nestedArray.flat();
console.log(flattenedArray);

const fullyFlattenedArray = nestedArray.flat(Infinity);
console.log(fullyFlattenedArray);

Output

[ 1, 2, [ 3, 4 ], 5, 6 ]
[ 1, 2, 3, 4, 5, 6 ]

As you can see, flat() can flatten an array to a certain depth, specified as an argument. If no argument is provided, the array is flattened to a depth of 1. In the second example above, we pass in the value Infinity as the argument to fully flatten the array, regardless of how many levels of nesting it has.

The flat() method is a convenient and efficient way to flatten arrays in modern JavaScript environments, but it may not be supported in older browsers or environments.

 

Method-3: Using the reduce() method

Another way to flatten an array is to use the Array.prototype.reduce() method, which applies a function to each element of the array and reduces the array to a single value. You can use this method to flatten an array by iterating through the array and concatenating each element with the flattened array.

Here's an example of how you could use reduce() to flatten an array:

function flattenArray(arr) {
    return arr.reduce(
        (acc, val) =>
            Array.isArray(val)
                ? acc.concat(flattenArray(val))
                : acc.concat(val),
        []
    );
}

const nestedArray = [1, [2, [3, 4], 5], 6];
const flattenedArray = flattenArray(nestedArray);
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]

Output

[ 1, 2, 3, 4, 5, 6 ]

In this example, we have a function called flattenArray() that takes an array as an argument. The function uses the reduce() method to iterate through the elements of the array, and applies a function to each element. The function checks if the current element is an array, and if it is, it calls itself recursively to flatten the array. The result of the recursive call is then concatenated with the flattened array. If the current element is not an array, it is simply concatenated with the flattened array.

This approach works well for shallow arrays and is efficient for arrays with many levels of nesting since it only requires a single iteration through the array. However, it may be less intuitive than the other approaches.

 

Summary

In summary, there are a few different ways to flatten an array in JavaScript, depending on your needs and the structure of the array you are working with. You can use the concat() method to iteratively concatenate the elements of the array, the flat() method to flatten the array to a certain depth, or the reduce() method to iteratively concatenate the elements of the array using a reducer function.

 

References

Array.prototype.concat() - JavaScript | MDN (mozilla.org)
Array.prototype.reduce() - JavaScript | MDN (mozilla.org)
Array.prototype.flat() - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment