I have 2 arrays like this:
blockedUsers = ['u1', 'u2', 'u3']
videoList = [
{
id: 1,
mp4URL: '...mp4',
user: {
id: 'u1',
name: 'User 1'
}
},
{
id: 2,
mp4URL: '...mp4',
user: {
id: 'u2',
name: 'User 1'
}
},
{
id: 3,
mp4URL: '...mp4',
user: {
id: 'u5',
name: 'User 1'
}
}
]
I want to remove blocked users from video array. At final I will get array has 1 video from u5. How to do that?
Thank you
Filter out elements where user id is not included in blocked users.
videoList.filter(v => !blockedUsers.includes(v.user.id))
You can filter the list by using the Array.prototype.includes() method.
const
blockedUsers = ['u1', 'u2', 'u3'],
videoList = [
{ id: 1, mp4URL: '...mp4', user: { id: 'u1', name: 'User 1' } },
{ id: 2, mp4URL: '...mp4', user: { id: 'u2', name: 'User 1' } },
{ id: 3, mp4URL: '...mp4', user: { id: 'u5', name: 'User 1' } }
],
allowedVideos = videoList.filter(({ user: { id } }) => !blockedUsers.includes(id));
console.log(allowedVideos);
.as-console-wrapper { top: 0; max-height: 100% !important; }
There are two ways
First way, you could filter the videoList and iterate to check if the user is in the blocked list. We could do this with .includes for blockedUsers, but this way will result in the complexity of O(n*m), given that n is the length of blockedUsers and m is the length of videoList
Second way, you could first turn the blockedUsers into a hash table using Set. This will reduce the query time complexity for blockedUsers from O(n) to O(1). In this way, the overall time complexity would be O(n + m), which is better than the first way
const blockedUsers = ["u1", "u2", "u3"]
const videoList = [ { id: 1, mp4URL: "...mp4", user: { id: "u1", name: "User 1", }, }, { id: 2, mp4URL: "...mp4", user: { id: "u2", name: "User 1", }, }, { id: 3, mp4URL: "...mp4", user: { id: "u5", name: "User 1", }, }, ]
const blockedUsersHashTable = new Set(blockedUsers)
const res = videoList.filter(
({ user: { id } }) => !blockedUsersHashTable.has(id)
)
console.log(res)
If time complexity is not your concern, just go with the first way.