Skip to content Skip to sidebar Skip to footer

Return Spreaded Array In Arrow Function

Let's assume i have this type of array: [ [1, 2], [3, 4] ] What i need to do is to get nested elements on the higher layer, to make it look like: [1, 2, 3, 4] I am trying to reach

Solution 1:

You can use the flat method of Array:

const inp = [ [1, 2], [3, 4] ];

console.log(inp.flat());

In your case, the spread syntax is not an operator that you can use in that way, that's why the error.

As @MarkMeyer correctly pointed out in the comments, the flat is not supported yet by Edge and Internet Explorer. In this case you could go for a solution with reduce:

const inp = [[1,2], [3,4]];
console.log(inp.reduce((acc, val) => acc.concat(...val), []));

Solution 2:

Array.from will produce an item for every item in the array passed in. It looks at the length of the passed in iterable and iterates over the indexes starting at 0. So no matter what you do in the callback (assuming it's valid), you're going to get an array of length 2 output if you pass in a two-element array.

reduce() is probably a better option here:

let arr = [ [1, 2], [3, 4] ]

let flat = arr.reduce((arr, item) => [...arr, ...item])
console.log(flat)

Solution 3:

You could create an iterator for the array and spread the array by using another generator for nested arrays.

function* flat() {
    for (var item ofthis.slice()) {
        if (Array.isArray(item)) {
            item[Symbol.iterator] = flat;
            yield* item
        } else {
            yield item;
        }
    }
}

var array = [[1, 2], [3, 4, [5, 6]]];

array[Symbol.iterator] = flat;

console.log([...array]);

Post a Comment for "Return Spreaded Array In Arrow Function"