This piece of code should return hits = ["Heather, "Heather", "Heather"] but it doesn't. I'm not quite sure what I am doing wrong.
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather", "fjdiafjdoisfhoids"];
var myName = "Heather";
var hits = [];
for(var i = 0; i < text.length; i++) {
if (text[i] === myName[i]) {
for(var j = i; j < (myName.length + i); j++); {
hits.push(text[j]);
}
}
}
4 Answers 4
You can use array filter function:
var hits = text.filter(function (obj) {
return obj === myName;
});
Snippet
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather", "fjdiafjdoisfhoids"];
var myName = "Heather";
var hits = text.filter(function (obj) {
return obj === myName;
});
console.log(hits);
16 Comments
var hits = text.filter(obj => obj === myName);Array.prototype.filter() either, right? IE8 doesn't support it. So now what, fall back to for loops? We move on. And the quicker we as a development community forget about the atrocities of the past, the better.Obligatory use this library answer. Here I use lodash:
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather", "something"],
myName = "Heather";
var hits = _.filter(text, _.matches([myName]);
Explanation on what's happening because this isn't intuitive at all. _.filter does the same thing as Array.prototype.filter except it's faster. You can run your own tests below to get an idea:
https://jsperf.com/array-filter-vs-lodash-filter-without-bias/2
The explanation I've heard is that traditional array operations implemented by lodash (map, reduce, filter, etc.) don't have to follow the implementation as detailed by the spec.
Anyways, _.filter takes two arguments: a collection (array or object) and function which returns true or false. If true, it'll return the item.
_.matches is a convenience function which returns a function that takes an argument and matches against the contents of the provided collection.
You could write the above another way:
var hits = _.filter(text, function(str) {
return str === myName
});
In lodash, we create functions all the time that basically executes an equality check. _.matches is just a convenience function to create equality check function.
Comments
Check against myName variable.
var text = ["Heather", "kfdjsalfjdai", "fdjafhjdksafh", "Heather", "Heather",
"fsomething"];
var myName = "Heather";
var hits = [];
for(var i = 0; i < text.length; i++) {
if (text[i] === myName) {
hits.push(text[i]);
}
}
console.log(hits);
Here is a working sample
2 Comments
:)text[i] will never === myName[i], because text is an array of strings, whereas myName is just one string. So for example, text[1] === "Heather", whereas myName[1] === "H". Any index of myName will just return one character.
var hits = text.filter(function(s){return s===myName})