Arshia Moghaddam
Arshia Moghaddam

Reputation: 538

find arrays that contain a string

I have a vuejs project and i want to implement a search component with a list component i got what i need from search component and passed it to list component and in it i have a computed function for filtering its list items

I tried this but does not work as i intended

 filteredItems() {
      return this.items.filter(item => {
        if (this.search != "") return item.includes(this.search);
        else return true;
      });
    }

in this code if i have such array as list items

items:[
   ['abc','def','ghi'],
   ['ajk,'lmn','opq']
]

and if i pass 'a' to my computed function i want both of those arrays but get nothing and i have to pass specifically 'abc' to only get first array and that is not how searching works.

can somebody help me to fix this?

Upvotes: 1

Views: 50

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

You need to use .some to check whether any of the array items contain the substring:

const items = [
   ['abc','def','ghi'],
   ['ajk','lmn','opq']
];
const doFilter = search => (
  items.filter(
    (arr) => arr.some((str) => str.includes(search))
  )
);
console.log(doFilter('a'));
console.log(doFilter('ab'));

Upvotes: 7

Related Questions