0

There are two chat rooms and each one is having two owners which are user object IDs. i would like to concatinate both the owners into one array so that i can find details of owners other than current user

  [ { owners: [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b ],
   _id: 5d6ccf5d55b38522a042dbb2,
    createdAt: 2019-09-02T08:14:21.734Z,
    updatedAt: 2019-09-02T08:14:21.734Z,
     __v: 0,
    id: '5d6ccf5d55b38522a042dbb2' },

  { owners: [ 5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d ],
    _id: 5d6dfd48e3b11807944348ba,
     createdAt: 2019-09-03T05:42:32.572Z,
     updatedAt: 2019-09-03T05:42:32.572Z,
      __v: 0,
   id: '5d6dfd48e3b11807944348ba' } ]


    const chatrooms = await ChatRoom.find({owners:{$all:[user._id]}})
    //the above code was run to get result in problem statement

    const owners = []
    chatrooms.forEach((chatroom) => {
        owners.push(chatroom.owners)
    })

i am expecting something like this

owners= [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b, 
5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d]

2 Answers 2

2

On newer browsers and node 11, you could use the flatMap method.

Something like this would work:

chatrooms.flatMap(room => room.owners)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap

And for older version, you'd do something like this:

const owners = []
chatrooms.forEach((chatroom) => {
  chatroom.owners.forEach(owner => owners.push(owner))
})
Sign up to request clarification or add additional context in comments.

3 Comments

can you please explain the flat map, how it works here
@vithushaji From the link: The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. So it takes all room owners and into an array and then flattens the array, resulting in single array with all owner ids.
if i want to remove user id from the newly created array. how shall we do it?
0

If you want to go all es6 like with javascript (making sure you are using recent browsers) you can use the array function reduce with the array concat method. Like so:

const owners = chatrooms.reduce((acc, chatroom) => acc.concat(chatroom.owners));

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.