Skip to content Skip to sidebar Skip to footer

How To Return Booleans Joined With && Inside Callback Function In Filter Method?

I am looking for an elegant way to generate booleans that will eventually be joined using && operator inside my callback function in filter method. I tried to loop through

Solution 1:

You could use Array#every for the filters array.

For a faster check, you could convert the filter values to lowercase in advance.

var preSearch = [["The Lord of the Rings", "J. R. R. Tolkien", "English", "1955", "150 milionów"], ["Le Petit Prince (The Little Prince)", "Antoine de Saint-Exupéry", "French", "1943", "140 milionów"], ["Harry Potter and the Philosopher's Stone", "J. K. Rowling", "English", "1997", "120 milionów"], ["The Hobbit", "J. R. R. Tolkien", "English", "1937", "100 milionów"], ["And Then There Were None", "Agatha Christie", "English", "1939", "100 milionów"], ["Dream of the Red Chamber", "Cao Xueqin", "Chinese", "1791", "100 milionów"]],
    filters = ["", "", "english", "19", "1"].map(s => s.toLowerCase()),
    result = preSearch
        .filter(row => filters.every((v, i) => row[i].toLowerCase().includes(v)));

console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 2:

You can do this by applying Array.every() and String.includes() like this:

var searchdata = this.preSearch.filter(row => {

    // this only returns true if our condition works for// index = 0, 1, 2, 3, 4return [0, 1, 2, 3, 4].every(index => {
        const rowContent = row[index].toLowerCase();
        const filterContent = filters[index].toLowerCase();

        // String.includes() is nicer than String.indexOf() here because// you don't need the ugly -1return rowContent.includes(filterContent);
    });
});

Post a Comment for "How To Return Booleans Joined With && Inside Callback Function In Filter Method?"