value - remove element from array javascript
Get item in sub array and put back to main array (5)
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 ?
var array_demo = [
['1st', '1595', '8886'],
['2nd', '1112']
]
var reduced_array = array_demo.reduce((reducedArray, elem) => {
elem.shift() // Remove the first item
return reducedArray.concat(elem)
}, [])
console.log(reduced_array)
Instead of
join()
use
Array.prototype.flat()
on the returned result of
map()
:
var array_demo = [
['1st', '1595', '8886'],
['2nd', '1112']
]
array_demo = array_demo.map(function(i) {
return i.slice(1);
}).flat();
console.log(array_demo);
In one liner using Arrow function(=>) :
var array_demo = [
['1st', '1595', '8886'],
['2nd', '1112']
]
array_demo = array_demo.map(i => i.slice(1)).flat();
console.log(array_demo);
You could also use
array.reduce
, and use it as follows:
array_demo.reduce( function(prev, curr, index) {
return prev.concat(curr.slice(1));
} ).slice(1);
Thing is, array.map, returns the result for each element in the array. So, in your example, it has two cycles:
- ['1st', '1595', '8886'] -> returns '1595,8886' because you used join()
- ['2nd', '1112'] -> returns '1112' also because you used join()
And you get that in an array -> ['1595,8886', '1112'].
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);
when we need a single accumulated values, we can use reduce funcions.
var array_demo = [
['1st', '1595', '8886'],
['2nd', '1112']
]
var l = array_demo.reduce((val, item)=> {
return val.concat(item.slice(1));
},[]);
console.log(l);