Search code examples
javascriptarraysdestructuring

Get item in sub array and put back to main array


I have a problem when get item in sub array and put back to main array by javascript. I have array like this:

var array_demo = [
    ['1st', '1595', '8886'],
    ['2nd', '1112']
]

I want to get result like this: ['1595','8886','1112']

But when I use this code:

array_demo.map(function(i) {
    return i.slice(1).join();
});

Result: ['1595,8886', '1112']

Can someone help me ?


Solution

  • You could destructure the array and take the rest without the first element and flatten this array using Array.flatMap.

    var array = [['1st', '1595', '8886'], ['2nd', '1112']],
        result = array.flatMap(([_, ...a]) => a);
    
    console.log(result);

    Alternatively Array.slice() works as well.

    var array = [['1st', '1595', '8886'], ['2nd', '1112']],
        result = array.flatMap(a => a.slice(1));
    
    console.log(result);