Skip to content

How do I search through an array using a string, which is split into an array?

I currently have a half solution to this, but I was wondering if there is a better way to write this. I have the following array with equipment deliveries:

var deliveries = ["14/02/2020, 11:47,cubicles,A32", "13/02/2020,11:48,relays,A59",etc....]

Which I search through using an input:

var pn = document.getElementById("PN").value;
pn = pn.split(" "); 

What I’m trying to achieve is to split the search word with spaces, and check if an index in the array contains all of these words. I currently search up to three words, since the code would become too long using my “solution”, if I searched for more. This is my code:

var sArray = []//search results
for(var i = 0; i < deliveries.length; i++){
    if (pn.length == 2) {
        if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])) sArray.push(deliveries[i]);
    else if (pn.length == 3) {
        if(new RegExp(pn[0],"i").test(deliveries[i]) && new RegExp(pn[1],"i").test(deliveries[i])&& new RegExp(pn[2],"i").test(deliveries[i])) sArray.push(deliveries[i]);
    else {if(new RegExp(pn[0],"i").test(deliveries[i])) sArray.push(deliveries[i])};

What would be the correct way to search using all the words in the pn array?

I tried saving the if statements as a string, adding code to the string for each index of pn and then using eval. This turned out to slow the search to a crawl though.

Any help would be appreciated.

Example added for a user searching for “cub a32”:

pn = "cub a32"

Which turns into:

pn = ["cub, "a32"]

Results in:

sArray = ["14/02/2020, 11:47,cubicles,A32"]



You could filter the array and check with every or some, depending if you want all or just one search string in an item of deliveries.

var deliveries = ["14/02/2020, 11:47,cubicles,A32", "13/02/2020,11:48,relays,A59"],
    input = "cub a32",
    pn = input.toLowerCase().split(' '),
    result = deliveries.filter(s => pn.every(v => s.toLowerCase().includes(v)));

User contributions licensed under: CC BY-SA
8 People found this is helpful