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

1.5 KiB

title subtitle lang slug createdAt excerpt tags type
Filter an array against another array Array vs Array. en array-vs-array 2022-06-08T14:24:06.000Z My peak javascript
nuxt.js
snippets

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:

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:

// 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…