Reuben
Reuben

Reputation: 141

How to include the entire length of arrays?

Below I created this filter method to only display what's found within the fullDetails array.

I apologize if this question is unclear and if I'm using the wrong terminology.

Right now it can work if I input each element individual (eg. fullDetails[0]). But the array has 4 elements. How can I write it so that it includes the entire length of array? (ie. [0] [1] [2] [3])?

let modItemList = this.props.items.filter(
        (item) => {
            return item.fullDetails[0].toLowerCase().indexOf(this.state.searchItems.toLowerCase()) !== -1;
        }
    );

Upvotes: 1

Views: 99

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

If your filter is supposed to keep items whose fullDetails array contains this.state.searchItems (case-insensitive), you're looking for the some method of arrays:

let lc = this.state.searchItems.toLowerCase(); // Do this once
let modItemList = this.props.items.filter(
    (item) => item.fullDetails.some(e => e.toLowerCase().indexOf(lc) !== -1)
);

some calls its callback for each entry in the array, stopping and returning true if the callback returns a truthy value (if it never does, some returns false).

Instead of indexOf, you could also use includes (ES2015, like let and arrow functions):

let lc = this.state.searchItems.toLowerCase(); // Do this once
let modItemList = this.props.items.filter(
    (item) => item.fullDetails.some(e => e.toLowerCase().includes(lc))
);

Upvotes: 6

baao
baao

Reputation: 73241

You can use every to check if every element matches.

let modItemList = this.props.items.filter(
    (item) => {
        return item.fullDetails.every(fullDetail => fullDetail.toLowerCase().indexOf(this.state.searchItems.toLowerCase()) !== -1);
    }
);

However, the plural in searchItems indicates that this could be an array either - so maybe you need to flip/enhance the logic here.

Upvotes: 0

Related Questions