0

I am mapping through two different array objects and comparing them using their id's

  const Users =[{"id":"1","name":"Ben"},{"id":"2","name":"Khloe"},{"id":"3","name":"Ayra"}];
  const Connects = [{userId: "1", status:"pending", type: 'skipped'}, {userId: "3", status:"pending", type: 'invited'}];
  
  const connectMap = Connects.reduce((map, { userId, type, status }) => {
    let connect = map.get(userId) || []
    connect.push(type, status)
    return map.set(userId, connect)
  }, new Map())
  
  const array = Users.map(({ id, name }) => ({
    name,
    type: (connectMap.get(id) || []).join(', '),
    status: (connectMap.get(id) || []).join(', '),
  }))
  
  console.info(array)

I am getting this as an output

[
  { name: 'Ben', type: 'skipped, pending', status: 'skipped, pending' },
  { name: 'Khloe', type: '', status: '' },
  { name: 'Ayra', type: 'invited, pending', status: 'invited, pending'
  }
]

So you'll notice the type & status keys are having two values separated with a comma, which is not what I want.

I want an output like this

[
      { name: 'Ben', type: 'skipped', status: 'pending' },
      { name: 'Khloe', type: '', status: '' },
      { name: 'Ayra', type: 'invited', status: 'pending'
      }
    ]

1 Answer 1

1

You need to separate out the status and type values inside connectMap - right now you just have one array for each, so of course

type: (connectMap.get(id) || []).join(', '),
status: (connectMap.get(id) || []).join(', '),

will return the same thing.

But because the input and output arrays look to all be one-to-one, it'd make more sense to .map. First turn the Connects into an object indexed by userId, then map the Users and look up the ID on that object for each user.

const Users =[{"id":"1","name":"Ben"},{"id":"2","name":"Khloe"},{"id":"3","name":"Ayra"}];
const Connects = [{userId: "1", status:"pending", type: 'skipped'}, {userId: "3", status:"pending", type: 'invited'}];

const connectsById = Object.fromEntries(
  Connects.map(({ userId, status, type }) => [userId, { type, status }])
);
const output = Users.map(({ id, name }) => ({
  name,
  ...(connectsById[id] || { status: '', type: '' })
}));
console.log(output);

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

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.