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.
Please what's the best way for me to achieve this?
CodePudding user response:
Here is another similar solution but with a bit modified syntax, I hope this will be helpful:
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 uniqueResult = (Object.values(arr.reduce(function(acc, item) {
if (!acc[item.message.user_id]) {
acc[item.message.user_id] = item;
}
return acc;
}, {})));
console.log(uniqueResult);
CodePudding user response:
Create a dictionary/object.
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)