Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array.map() not returning a single array

I have the code below which I expect to map the result from the nested array and return a single array having both id's but I get 2 arrays instead. Can someone please guide me on what I'm doing wrongly?

arrayVal = [{
    sources: {
      data: [{
        id: 1
      }]
    }
  },
  {
    sources: {
      data: [{
        id: 2
      }]
    }
  }
]

for (let sub of arrayVal) {
  let result = sub.sources.data.map(x => (x.id))
  console.log(result)
}
like image 350
Hopez Avatar asked Mar 10 '26 17:03

Hopez


2 Answers

Right now, you're calling map for each element in arrayVal, so you get two arrays. Use reduce instead, to transform an array of objects into another array that's not necessarily one-to-one with the input elements:

const arrayVal=[{sources:{data:[{id:1}]}},{sources:{data:[{id:2}]}}];

const result = arrayVal.reduce((a, { sources: { data } }) => (
  [...a, ...data.map(({ id }) => id)]
), []);
console.log(result)
like image 161
CertainPerformance Avatar answered Mar 13 '26 07:03

CertainPerformance


Try following

var arrayVal = [{sources: {data: [{id: 1}]}},{sources: {data: [{id: 2}]}}];

// Create an array on sources.data and merge it into 1 collection (array)
var result = arrayVal.reduce((a, c) => [...a, ...c.sources.data.map(({id}) => id)], []);

console.log(result);

For reference, Array.reduce

Also, you can improve your code as follows

var arrayVal = [{sources: {data: [{id: 1}]}},{sources: {data: [{id: 2}]}}];

let result = [];
for (let sub of arrayVal) {
  result.push(sub.sources.data.map(x => (x.id)));
}
console.log([].concat(...result))
like image 35
Nikhil Aggarwal Avatar answered Mar 13 '26 06:03

Nikhil Aggarwal