2

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"]
1
  • 2
    do you have an example for a seach? with expected result? Commented Feb 14, 2020 at 12:14

1 Answer 1

3

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)));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.