Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- // see if the array is already flattened
- // returns true or false
- const isArrayFlattened = function($array) {
- if (!$array) {
- return true;
- }
- for (const item of $array) {
- if (item instanceof Array) {
- return false;
- }
- }
- return true;
- };
- // main function to flatten the arrays. The use of Array.prototype.reduce is so that each iteration
- // a (potential) layer of square brackets is removed.
- // This is ensured by that [1].concat(2).concat(3) returns the same value as
- // [1].concat([2, 3]), which is [1, 2, 3] for both
- const flatten = function($array) {
- while (!isArrayFlattened($array)) {
- $array = $array.reduce((previous, item) => {
- return previous.concat(item);
- }, []);
- }
- return $array;
- };
- console.log(flatten([])); // []
- console.log(flatten([1, [2], 3])); // [1, 2, 3]
- console.log(flatten([[1, 2], 3])); // [1, 2, 3]
- console.log(flatten([[[1], 2], 3])); // [1, 2, 3]
- console.log(flatten([[[[1]], 2], 3])); // [1, 2, 3]
- console.log(flatten([[1], [2], [3]])); // [1, 2, 3]
- console.log(flatten([[[[1], [2]], [3]]])); // [1, 2, 3]
Add Comment
Please, Sign In to add comment