Reputation: 2081
I am trying to find the most efficient way, in javascript(I'm using node.js), of taking a user's input and pairing the inputs to find exact array matches. I know how to do this without performance in mind, my main goal is the best performance algorithm.
For example:
User input(can have up to 15 animals): dog bear cat lion snake
The api data(in json), where the animal array length is always 2:
{
data: [
{ animals: ["cat", "dog"], content: "demo content 1." },
{ animals: ["snake", "cat"], content: "demo content 2." },
{ animals: ["bird", "mouse"], content: "demo content 3." }
]
}
I want to find all the animal matches, in this case, the user input would match to dog cat
cat snake
animals. I would be able to access "demo content 1." and "demo content 2.".
Upvotes: 1
Views: 89
Reputation: 147206
One fairly efficient method would be to use Array.reduce
on the data
array, checking that each value in data.animals
is in the user input and if so, pushing the content to the output:
const apidata = {
data: [
{ animals: ["cat", "dog"], content: "demo content 1." },
{ animals: ["snake", "cat"], content: "demo content 2." },
{ animals: ["bird", "mouse"], content: "demo content 3." }
]
}
const userinput = ['dog', 'bear', 'cat', 'lion', 'snake']
const content = apidata.data.reduce((c, o) => {
if (o.animals.every(a => userinput.includes(a)))
c.push(o.content);
return c;
}, []);
console.log(content)
Upvotes: 2