Home > Blockchain >  combine array of array objects into single array
combine array of array objects into single array

Time:10-09

this is my input

[
  [
    { jobId: 1, requiredNumber: 1, acceptableRate: 80 },
    { jobId: 2, requiredNumber: 2, acceptableRate: 80 },
    { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
    { jobId: 4, requiredNumber: 1, acceptableRate: 80 }
  ],
  [ { jobId: 2, requiredNumber: 1, acceptableRate: 95 } ],
  null
]

I have been trying to combine this array of objects into a single array, i have tried using .reduce() but i wasn't successful and my output was like this

[
  { jobId: 1, requiredNumber: 1, acceptableRate: 80 },        
  { jobId: 2, requiredNumber: 2, acceptableRate: 80 },        
  { jobId: 3, requiredNumber: 3, acceptableRate: 80 },        
  { jobId: 4, requiredNumber: 1, acceptableRate: 80 }
] [ { jobId: 2, requiredNumber: 1, acceptableRate: 95 } ] null

it was still 2 arrays not a single array

my expected output is

[
    { jobId: 1, requiredNumber: 1, acceptableRate: 80 },
    { jobId: 2, requiredNumber: 2, acceptableRate: 80 },
    { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
    { jobId: 4, requiredNumber: 1, acceptableRate: 80 },
    { jobId: 2, requiredNumber: 1, acceptableRate: 95 }
]

CodePudding user response:

Flatten the array, and then filter out the objects.

const data=[[{jobId:1,requiredNumber:1,acceptableRate:80},{jobId:2,requiredNumber:2,acceptableRate:80},{jobId:3,requiredNumber:3,acceptableRate:80},{jobId:4,requiredNumber:1,acceptableRate:80}],[{jobId:2,requiredNumber:1,acceptableRate:95}],null];

const out = data.flat().filter(obj => obj);
console.log(out);

const data=[[{jobId:1,requiredNumber:1,acceptableRate:80},{jobId:2,requiredNumber:2,acceptableRate:80},{jobId:3,requiredNumber:3,acceptableRate:80},{jobId:4,requiredNumber:1,acceptableRate:80}],[{jobId:2,requiredNumber:1,acceptableRate:95}],null];

const out = data.flat().filter(Boolean);
console.log(out);

CodePudding user response:

you should use flat flat function
with a filter to filter out all the null filter function

CodePudding user response:

It could be even simpler than using flat or reduce. It could be just this (using the ... spread operator):

[
  ...[
    { jobId: 1, requiredNumber: 1, acceptableRate: 80 },
    { jobId: 2, requiredNumber: 2, acceptableRate: 80 },
    { jobId: 3, requiredNumber: 3, acceptableRate: 80 },
    { jobId: 4, requiredNumber: 1, acceptableRate: 80 }
  ],
  ...[ 
    { jobId: 2, requiredNumber: 1, acceptableRate: 95 } 
  ]
]
  • Related