blackrox
blackrox

Reputation: 231

How to filter an array in array of objects in Javascript?

 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!

Upvotes: 3

Views: 38776

Answers (2)

Kirill Savik
Kirill Savik

Reputation: 1278

filter() -> 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);

Upvotes: 11

Krokodil
Krokodil

Reputation: 1480

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

Upvotes: 3

Related Questions