1

I need to get values from multiple keys from an array of object.

trip = [
    {sp: 'cbe', ep: 'tpr'}, 
    {sp: 'tpr', ep: 'erd'}, 
    {sp: 'erd', ep: 'blr'}
];

The output should be ["cbe", "tpr", "erd", "blr"]

what I tried is posted as an answer and it works but I used two maps to get the desired output. I know there should be a way better than my answer.

Here is my code on stackblitz

4 Answers 4

3

The new flatMap function can be used here, but be aware of limited browser support

trip = [
    {sp: 'cbe', ep: 'tpr'}, 
    {sp: 'tpr', ep: 'erd'}, 
    {sp: 'erd', ep: 'blr'}
];

res = [ ...new Set(   trip.flatMap(Object.values)    )]

console.log(res)

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

2 Comments

can you tell ,me what flatmap does?
@anonymous Just follow the link in the answer!
1

Here's another way: (updated to aggregate all keys instead of explicit keys)

const trip = [
    {sp: 'cbe', ep: 'tpr'}, 
    {sp: 'tpr', ep: 'erd'}, 
    {sp: 'erd', ep: 'blr'}
];

const t = Array.from(trip.reduce((a, el) => {
    for (let key in el) a.add(el[key]);
    return a;
}, new Set()));

console.log(t);

1 Comment

I don't think you explicitly need to provide an empty array to the Set constructor. Also, the final result here will be a Set not an array. You can fix that with Array.from(trip.reduce...).
1

    const trip = [
        {sp: 'cbe', ep: 'tpr'}, 
        {sp: 'tpr', ep: 'erd'}, 
        {sp: 'erd', ep: 'blr'}
    ];
    const r = trip.map( m => {
      return m.sp
    });
    const s = trip.map( m => {
      return m.ep
    });
    console.log(Array.from(new Set(r.concat(s))));

Comments

0

If you are O.K. with not-so-much readable one-liner…

trip = [{
    sp: 'cbe',
    ep: 'tpr'
  },
  {
    sp: 'tpr',
    ep: 'erd'
  },
  {
    sp: 'erd',
    ep: 'blr'
  }
];

const res = [...new Set([].concat.apply([], trip.map(item => Object.values(item))))];

console.log(res);

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.