Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the first unique item of a deep-nested object in an array in Javascript

I have an array of objects that looks like this:

const arr  = [
{id: 123, message: { user_id: 4, text: 'fish'}}
{id: 456, message: { user_id: 4, text: 'cow'}}
{id: 789, message: { user_id: 5, text: 'chicken'}}
{id: 010, message: { user_id: 5, text: 'turkey'}}
]

I want to return the first item in the array where the message.user_id is unique. I’m expecting a result like this:

newArr  = [
{id: 123, message: { user_id: 4, text: 'fish'}}
{id: 789, message: { user_id: 5, text: 'chicken'}}
]

I can’t seem to find any solution for this. I’m dealing with dynamic data so I can’t exactly hardcode the user_id and the array I’m working with contains a lot of elements so I’m trying as much as possible to avoid looping through.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please what’s the best way for me to achieve this?

>Solution :

  1. Create a dictionary/object.

  2. Iterate through the array and check if
    the id is a key in it

    2.1 If yes, skip

    2.2 If not:

    • Add the row to the output
    • Add the user_id to the dictionary.
const arr  = [
{id: 123, message: { user_id: 4, text: 'fish'}},
{id: 456, message: { user_id: 4, text: 'cow'}},
{id: 789, message: { user_id: 5, text: 'chicken'}},
{id: 010, message: { user_id: 5, text: 'turkey'}}
]

const userIDs = {}

const output = arr.reduce((acc, item) => {
  const user_id = item.message.user_id
  if (userIDs[user_id]) return acc

  acc.push(item)
  userIDs[user_id] = true;
  return acc
},[])

console.log(output)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading