Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
Return different objects using map without pushing into array

The following code in JavaScript:

const mixedObjects = [1,2,3].map(num => {
    return { a: 'always same' }
});

returns the following result:

[
  {a: 'always same'},
  {a: 'always same'},
  {a: 'always same'}
]

I want to return the following without declaring an empty array outside and then pushing into it. So do it all inside the map. Is this possible?

What I want to return:

[
  {a: 'always same'},
  {b: 1},
  {a: 'always same'},
  {b: 2},
  {a: 'always same'},
  {b: 3}
]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use Array.flatMap(), and return a tuple of the 2 objects on each iteration. The flatMap would create a flattened array of objects.

const mixedObjects = [1,2,3].flatMap(b => {
  return [{ a: 'always same' }, { b }]
});

console.log(mixedObjects);

about 4 years ago · Juan Pablo Isaza Report

0

You can combine map and flat methods:

const mixedObjects = [1,2,3].map(num => {
    return [{ a: 'always same' }, {b: num}];
}).flat();

P. S. Or use flatMap method as suggested by Ori Drori.

about 4 years ago · Juan Pablo Isaza Report

0

... reduce based solutions work as well ...

console.log(
  [1,2,3].reduce((result, b) =>
    [...result, { a: 'always same' }, { b }] , []
  )
);
console.log(
  [1,2,3].reduce((result, b) =>
    result.concat({ a: 'always same' }, { b }), []
  )
);
console.log(
  [1,2,3].reduce((result, b) => {
  
    result.push({ a: 'always same' }, { b });
    return result;

  }, [])
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!