I have a search function which works good, but I want to modify it little bit. Let say I have some search query:
XXX
It should show the series which contains the input XXX
XXX 130
It should show the families which contains XXX130 in its name
XXX 130 6 W
It should show both families with name including XXX130 and families which has wattage: 6
.
111-1935
It should show the families with that productCode
.
const series = [{
id: 1,
name: 'XXX100 MARKER',
},
{
id: 2,
name: 'XXX100',
},
// and etc
];
const families = [{
id: 1,
wattage: 6,
seriesId: 1,
productCode: '111-1935',
name: 'XXX120-GB LED',
},
{
id: 2,
seriesId: 1,
wattage: 6,
productCode: '111-1947',
name: 'XXX130-GB LED',
},
{
id: 3,
seriesId: 1,
wattage: 6,
productCode: '111-1950',
name: 'XXX130-GB-TW LED',
},
{
id: 4,
seriesId: 1,
wattage: 6,
productCode: '111-1970',
name: 'XXX130-GB-CC LED',
},
];
let filteredFamilies = [];
let matchingSeries = [];
let terms = [];
const handleSearch = () => {
console.clear();
let searchText = document.getElementById('term').value;
terms = searchText.split(' ').map(term => term.toLowerCase());
matchingSeries = series.filter(s => {
return terms.every(term => s.name.toLowerCase().includes(term));
});
filteredFamilies = families.filter(family => {
let seriesName = series.find(s => s.id === family.seriesId).name.toLowerCase();
return terms.every(term => {
const wattageStr = family.wattage.toString();
const wattageWithW = wattageStr + 'w';
return (
seriesName.includes(term) ||
family.name.toLowerCase().includes(term) ||
wattageStr.includes(term) ||
wattageWithW.includes(term) ||
family.productCode.toLowerCase().includes(term)
);
});
});
console.log(filteredFamilies);
};
<input type="text" id="term" />
<button onclick="handleSearch()">Search</button>
So, if user types XXX 130 6
(or XXX 130 6W
) it should show results which include XXX
, 130
and 6
in it. How can I achieve it?