-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
  • 5,717
  • 7
  • 51
  • 110

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,215
  • 2
  • 13
  • 22
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ѕн
  • 68,816
  • 17
  • 108
  • 129
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,411
  • 2
  • 6
  • 18