Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 657
Nghia Phan Avatar asked Sep 18 '19 08:09

Nghia Phan


1 Answers

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);
like image 150
Nina Scholz Avatar answered Sep 28 '22 02:09

Nina Scholz