0 day streak
javascript / beginner
Snippet

Filtering an Array of Strings for Search Suggestions

Array.prototype.filter creates a new array containing only the elements that satisfy a provided callback condition. In this component, it narrows down the list of items based on the user's input query in real time.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React, { useState } from 'react';
function SearchList({ items }) {
const [query, setQuery] = useState('');
const matchingItems = items.filter((item) =>
item.toLowerCase().includes(query.toLowerCase())
);
return (
<div>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
<ul>
{matchingItems.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
}
react
Breakdown
1
const matchingItems = items.filter((item) =>
Applies the array filter method to iterate over each string element in the list.
2
item.toLowerCase().includes(query.toLowerCase())
Performs a case-insensitive check to see if the current string contains the search substring.