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?

2

4 Answers 4

1

Use the flat function:

var a = [1,2,[3,4],[5,6]] ;
a = a.flat();
console.log(a);

Sign up to request clarification or add additional context in comments.

Comments

0
var array = [1,2,[3,4],[5,6]];
var newArray = [].concat(...array);
console.log(newArray); // [1, 2, 3, 4, 5, 6]

Comments

0

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]);

Comments

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.