Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  149] [ 7]  / answers: 1 / hits: 12254  / 4 Years ago, wed, july 15, 2020, 12:00:00

I have an array of objects with the following structure


arr = [ { name: "abc" , items: ["itemA","itemB","itemC"], days :138} ,
{ name: "def" , items: ["itemA1","itemB2","itemC1"], days :157} ,
{ name: "hfg" , items: ["itemAN","itemB7","itemC7"], days :189} ]


This array needs to be filtered based on the search input passed. I was able to achieve the same for the name , where days is not getting filtered.


Also can someone help how to search across items array too so it filters the rows based on input passed


This is what I have tried


  handleSearch = (arr, searchInput) => {
let filteredData= arr.filter(value => {
return (
value.name.toLowerCase().includes(searchInput.toLowerCase()) ||
value.days.toString().includes(searchInput.toString())
);
});
console.log(filteredData);
//this.setState({ list: filteredData });
}



More From » arrays

 Answers
3

You can use Array#some and then perform the same kind of match that you've already done :



The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.



  handleSearch = (arr, searchInput) => {
const filteredData = arr.filter(value => {
const searchStr = searchInput.toLowerCase();
const nameMatches = value.name.toLowerCase().includes(searchStr);
const daysMatches = value.days.toString().includes(searchStr);
const oneItemMatches = value.items.some(item => item.toLowerCase().includes(searchStr));

return nameMatches || daysMatches || oneItemMatches;
});
console.log(filteredData);
//this.setState({ list: filteredData });
}

[#3174] Monday, July 13, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;