Merge arrays to one array after filtering
Can also solve using the Reduce function from Array.prototype.
var newResults = results.reduce(function(acc, curr) {
return acc.concat(curr.locations)
},[]
)
hope this helps
You don't need filter
here. Just use map
method by passing a callback provided function which is applied for every item on the array.
let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }, ];
const locationIds = [].concat(...results.map(s => s.locations));
console.log(locationIds);
You could taka a Array#flatMap
with the wanted property. If the property is not given, add a default array || []
.
let results = [{ id: '1', locations: ['aaaa', 'bbbbbb', 'cccccc'] }, { id: '2', locations: [] }, { id: '3', locations: ['ddd', 'aaadsad', 'sefd'] }, { id: '4', locations: ['ffff', 'eeee', 'sfdsfsd'] }],
locationIds = results.flatMap(({ locations }) => locations);
console.log(locationIds);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can try with flatMap()
:
The
flatMap()
method first maps each element using a mapping function, then flattens the result into a new array. It is identical to amap()
followed by aflat()
of depth 1, butflatMap()
is often quite useful, as merging both into one method is slightly more efficient.
let results = [{
id: '1',
locations: ['aaaa', 'bbbbbb', 'cccccc']
},
{
id: '2',
locations: []
},
{
id: '3',
locations: ['ddd', 'aaadsad', 'sefd']
},
{
id: '4',
locations: ['ffff', 'eeee', 'sfdsfsd']
},
];
const locationIds = results.flatMap(i => i.locations);
console.log(locationIds);