Reputation: 6501
I'm trying to implement a dropdown component, and this is what I have so far:
I'm wondering if there is a better way to get these suggestions on top? It kind of works right now, where the name is one word, but if the test data is full of objects, such as,
const testData = [
{ name: 'abc 123' },
{ name: 'def 123' },
. . .
]
Then it correctly recognises the matches, but it doesn't order them correctly, because it doesn't sort the suggestions array after the reduce
.
Upvotes: 0
Views: 29
Reputation: 6525
You could just chain an array.sort()
on to your reduce function since it returns an array. The reason for localCompare
in the sort function is because we are sorting strings.
const dropDownOpionsRest = testData.reduce((acc, item) => {
const match = regex.test(item.name);
console.log("match", item, match);
if (match) {
dropDownSuggestions.push(item);
} else {
acc.push(item);
}
return acc;
}, []).sort((a, b) => a.name.localeCompare(b.name));
dropDownSuggestions.sort((a, b) => a.name.localeCompare(b.name));
console.log([...dropDownSuggestions, ...dropDownOpionsRest]);
Upvotes: 1