0

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}
]
1
  • [1,2,3].reduce((result, b) => [...result, { a: 'always same' }, { b }] , []); Commented Oct 14, 2021 at 21:31

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

excellent thank you, is flatMap new? Is it supported for modern browsers the same way if I was to do it using map and push into array?
It's relatively new (much newer than push), but it's support by all modern browsers.
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.

Comments

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.