0

I am trying to spread the inner array elements of an array but couldn't figure it out how it works.

Input:

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

Output:

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

How do I convert the first array into 2nd one?

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
Reddy
  • 11
  • 4
    [`Array.prototype.flat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) – p.s.w.g May 30 '19 at 17:24
  • 3
    Possible duplicate of [Merge/flatten an array of arrays](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) – Amit Chauhan May 30 '19 at 17:27

4 Answers4

1

You could take a generator for the array which checks the lement and for arrays, it returns the nested elements.

function* flat() {
    var i = 0;
    while (i < this.length) {
        if (Array.isArray(this[i])) {
            this[i][Symbol.iterator] = flat;
            yield* this[i];
        } else {
            yield this[i];
        }
        i++;
    }
}

var array = [1, 2, [3, 4], [5, 6], [7, [8, 9]]];
array[Symbol.iterator] = flat;

console.log([...array]);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

Use the flat function:

var a = [1,2,[3,4],[5,6]] ;
a = a.flat();
console.log(a);
Simon C
  • 9,008
  • 3
  • 33
  • 53
Vishnu
  • 862
  • 6
  • 11
0
var array = [1,2,[3,4],[5,6]];
var newArray = [].concat(...array);
console.log(newArray); // [1, 2, 3, 4, 5, 6]
0

The term is "flattening" - here's a simple one-level flattening function:

const arr = [1, 2, [3, 4], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(curr), []);
console.log(flatten(arr));
.as-console-wrapper { max-height: 100% !important; top: auto; }

Deeply nested arrays require a different approach - here's a recursive function:

const arr = [1, 2, [3, 4, "a", ["b", "c"]], [5, 6]];
const flatten = a => a.reduce((acc, curr) => acc.concat(Array.isArray(curr) ? flatten(curr) : curr), []);
console.log(flatten(arr));
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67