const books = [{
id: "1",
title: "Book title",
areas: ["horror", "mystery"]
}, {
id: "2",
title: "Book title 2",
areas: ["friendship", "love", "history"]
},
{
id: "2",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];
This is my array of books and I want to make a new array depending on the areas. For example if user clicks on button - Horror, then I want to load only books that have horror in their -areas-, Im newbie in JS and I cant find a right way to do it. I want to make a new array named filteredBooks. Thank you for your help!
const books = [{
id: "1",
title: "Book title",
areas: ["horror", "mystery"]
}, {
id: "2",
title: "Book title 2",
areas: ["friendship", "love", "history"]
},
{
id: "2",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];
This is my array of books and I want to make a new array depending on the areas. For example if user clicks on button - Horror, then I want to load only books that have horror in their -areas-, Im newbie in JS and I cant find a right way to do it. I want to make a new array named filteredBooks. Thank you for your help!
Share Improve this question asked Sep 7, 2021 at 16:42 blackroxblackrox 2312 gold badges4 silver badges17 bronze badges 6 | Show 1 more comment2 Answers
Reset to default 11filter()
-> uses a callback function the return value of which decides what will be returned in the filtered array. If return value is true, the item is included in the resultant array.
includes()
-> searches for something in an array of items using ==
equality
const books = [{
id: "1",
title: "Book title",
areas: ["horror", "mystery"]
}, {
id: "2",
title: "Book title 2",
areas: ["friendship", "love", "history"]
},
{
id: "3",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];
const filterValue = "horror";
const filteredBooks = books.filter(val => val.areas.includes(filterValue));
console.log(filteredBooks);
Since there is already a great answer (by @Kirill Savik) for finding a book by a singular genre, I'll take this opportunity to expand on the given answer so that it can take in an array of genres from which to show books with at least one of these genres.
Take a look at this snippet:
const books = [
{
id: "1",
title: "Book title",
areas: ["horror", "mystery"]
},
{
id: "2",
title: "Book title 2",
areas: ["friendship", "love", "history"]
},
{
id: "2",
title: "Book title 3",
areas: ["friendship", "scifi"]
}
];
function filter_books(filters) {
const filteredBooks = [];
filters.forEach(filterValue => {
filteredBooks.push(...books.filter(val => val.areas.includes(filterValue)));
});
console.log(filteredBooks);
};
filter_books(["horror", "scifi"]); // Outputs all books which have one or more of these ^ genres
Array.includes()
method. – Barmar Commented Sep 7, 2021 at 16:43