Find The First Matching Value When Comparing Two Arrays Javascript
Solution 1:
You're returning false on the first non-match, whereas you should continue iterating.
move the return "no match"
to after everything has been iterated through.
You can alternatively also use the indexOf
here:
function findTheBreed(dogs) {
var breeds = ["terrier", "mix", "lab", "hound"];
for(let i = 0; i < dogs.length; i++) {
if(breeds.indexOf(dogs[i]) != -1){
return dogs[i];
}
}
return "no match";
}
One other (in my opinion the best) route would be to use the Array.filter functionality and retrieve the entire array of matches.
var breeds = ["terrier", "mix", "lab", "hound", "snickerdoodle"];
var filtered = breeds.filter(
function (elem) {
return dogs.indexOf(elem) != -1
}
);
return filtered;
Solution 2:
It would be simpler to turn one array into a dictionary and do a direct lookup.
For example, if dog is turned into a dictionary
var dictionary = {};
for(var i=0;i<dogs.length;i++){
dictionary[dogs[i]] = true;
}
for(var i=0;i<breeds.length;i++){
if(dictionary[breeds[i]] === true) return true; //found match
}
Solution 3:
Or shorter:
var findtheBreed=dogs=>["terrier","mix","lab","hound"].find(breed=>dogs.find(dog=>dog===breed))||"no match";
alert(findtheBreed(["pug","husky","hound","poodle"]));
http://jsbin.com/mubatiyebo/edit?console
using Array.prototype.find , Arrow functions and the brilliant OR operator...
Solution 4:
To fix your implementation, move the return "no match"
out of the loop body to the end of your findTheBreed
function.
However, you can find the first match faster - in constant time - by leveraging constant time Set.has
lookup:
function match(dogs, breeds) {
return dogs.find(Set.prototype.has, new Set(breeds));
}
let dogs = ["pug", "husky", "hound", "poodle"];
let breeds = ["terrier", "mix", "lab", "hound"];
console.log(match(dogs, breeds));
Also, I think you should consider renaming your arrays as there is currently no distinction between a dog
and a breed
. Also, you might consider declaring the breeds
as a Set
from the beginning on to avoid redundant conversion.
Solution 5:
You're returning out of the function too early. If you want the same data structure, maybe try this:
var dogs = ["pug", "husky", "hound", "poodle"];
function findBreed(dogs) {
var breeds = ["terrier", "mix", "lab", "hound"];
for (let i = 0; i < dogs.length; i++){
var dog = dogs[i];
var successIdx = breeds.indexOf(dog)
if (successIdx !== -1){
return dog
}
}
return "no match"
}
Post a Comment for "Find The First Matching Value When Comparing Two Arrays Javascript"