📜  javascript array flatten (1)

📅  最后修改于: 2023-12-03 15:16:04.485000             🧑  作者: Mango

JavaScript Array Flatten

When working with arrays in JavaScript, there might be times when we need to flatten a nested array into a single-dimensional array. This is where the flatten method comes in handy.

What is a Nested Array?

A nested array is an array that contains one or more arrays within it. For example:

const nestedArray = [[1, 2], [3, 4], [5, 6]];
How Does flatten Work?

The flatten method in JavaScript is used to flatten a nested array. It does this by recursively flattening each nested array until all the elements are in a single-dimensional array.

Example Usage

Here's an example of how to use the flatten method:

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

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

If you're working with an older version of JavaScript that doesn't have the flatten method, you can use the following polyfill:

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

You can then use the flatten method as shown in the example usage.

Conclusion

The flatten method is a powerful tool for working with nested arrays in JavaScript. It simplifies the process of flattening a nested array into a single-dimensional array.