I am trying to create a search/filter function that allows users to filter an array of JS objects which returns an array populated with data matching the search query.
I wish to be able to search multiple properties in one query so for example; if I search HKG it would return all 3 of the objects but if I searched HKG 12345 it would return the first object in the array.
Another example would be if I were to search 8 it would return the first 2 objects in the array from sumOfContainers property matching the query but if I searched 8 SAV it would return only the first object.
results = [];
objects = [
{laneId:"12345", lane:"HKG-SAV", equipmentType:"20'STD", sumOfContainers: "8", baseline:"$1234", new:"$1234", newSaving:"$1234"},
{laneId:"12346", lane:"HKG-FRA", equipmentType:"20'STD", sumOfContainers: "8", baseline:"$1234", new:"$1234", newSaving:"$1234"},
{laneId:"12347", lane:"HKG-LAX", equipmentType:"20'STD", sumOfContainers: "9", baseline:"$1234", new:"$1234", newSaving:"$1234"},
];
const Search = (toSearch) => {
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
results.push(objects[i]);
}
}
}
}
The problem with my attempt is that it will return duplicate data. I have come across a lot of posts online but I am finding difficulty trying to find posts seeking a similar result.
I am trying to achieve this with native JavaScript.
breakright after thepush. And don't forget toreturn results.Array.from(new Set(results))would make the results unique.objects.filterwould probably be helpful, but these conditions (e.g. being able to search “HKG 12345”) are a bit complex.