website-astro/src/content/fragments/en/array-vs-array.md

65 lines
1.5 KiB
Markdown
Raw Normal View History

2022-12-28 10:36:15 +01:00
---
title: Filter an array against another array
subtitle: Array vs Array.
lang: en
slug: "array-vs-array"
createdAt: "2022-06-08T14:24:06.000Z"
excerpt: My peak javascript
tags: ["nuxt.js"]
2023-05-09 12:26:03 +02:00
type: snippets
2022-12-28 10:36:15 +01:00
---
## Context
For a project, I had to come up with a way to filter an array of objects based on another array of strings.
In other words, I needed to include every object which `user` property was found in the second array.
Here is an example:
```javascript
const skills = [
{
name: "Be awesome",
user: "Jean",
},
{
name: "Great jokes",
user: "Jacques",
},
{
name: "Heavy sleeper",
user: "Jean",
},
{
name: "Heavy sleeper",
user: "Beatriz",
},
];
const selectedUsers = ["Jean", "Beatriz"];
```
I thought it would be pretty easy but I guess I'm not familiar enough with javascript 😬
## My solution
After a bit of thinking, I came up with the following statement:
> I need to filter the skills based on which users are selected. So I need to loop over the `selectedUsers` array and filter the skills according to their `user` value.
After a bit more trials and errors, this is the code I ended up using in a `computed property`:
```javascript
// index.vue
const filteredSkills = selectedUsers.map((user) => {
return skills.filter((skill) => {
return skill.user === user;
});
});
```
I used `map()` in order to loop on the second array and used its string value to only include the corresponding skills with `filter()`.
I'm pretty sure there is a better way to do it though…