-3

I want reduce an array of object, eg.:

const users = [
    {id: 1, username: 'foo'}, 
    {id: 2, username: 'bar'}, 
    {id: 3, username: 'baz'}
];

to an array of id, eg.:

users.reduce( magicReducer ); // output: [1,2,3]

is possible?

ar099968
  • 6,963
  • 12
  • 64
  • 127

3 Answers3

3

This should solve the problem for you !

const users = [{id: 1, username: 'foo'}, {id: 2, username: 'bar'}, {id: 3, username: 'baz'}];

console.log(users.map(user => user.id))
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
1

You don't need reduce for the required magic, you can simply use array .map() for this like:

const users = [{id: 1, username: 'foo'}, {id: 2, username: 'bar'}, {id: 3, username: 'baz'}];
const res = users.map(({id}) => id);

console.log(res)
palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

try this

const users = [
    {id: 1, username: 'foo'}, 
    {id: 2, username: 'bar'}, 
    {id: 3, username: 'baz'}
];

ids=users.map(x=>x.id)
console.log(ids)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18