After some web scraping I have an array of names called someObjArr
.
Array looks like this:
[ { name: Joe 'Panik' } ]
I want to check if a name exists in this array and here is my code:
For Example:
var someObjArr = [];
var filter = $('a.player-link').each(function(i, element) {
var text = $(this).text();
if(someObjArr[i] == undefined){
someObjArr[i] = {};
};
someObjArr[i].name = text;
function nameExistsInArray(name, array) {
for(var i = 0; i < array.length; i++)(function(obj) {
if(obj.name == name) {
return true;
}
})
return false;
};
var exists = nameExistsInArray('Joe Panik', [{ name: 'Joe Panik' }]);
console.log(exists);
});
The output from this script return false fir every item in the array.
1 Answer 1
How about something like this?
function nameExistsInArray(name, array) {
for(var i = 0; i < array.length; i++) {
if(array[i].Name == name) {
return true;
}
}
return false;
};
Usage:
var exists = nameExistsInArray('Joe Panik', [{ Name: 'Joe Panik' }]);
Explanation: You want to determine if some name of type string
is equal to one of the Name
properties of the object
s in an array
.
In our function, we'll pass a string
name and an array
of object
s with Name
properties. Then, we'll iterate through each obj
in array
using a for
loop, and then we'll access the Name
property and compare it with the name
argument. When we see it, return true
, but if we've iterated through every element and haven't found a match, we'll return false
.
-
1
Array.forEach
uses a closure. In your example,nameExistsInArray
will always returnfalse
. Use a normalfor
loop.thoughtrepo– thoughtrepo2015年07月25日 22:37:56 +00:00Commented Jul 25, 2015 at 22:37 -
I updated my OP with your code. I had to add a little because obj is undefined in yours. Unfrtunatly it still produces a false for each item in the array.CiscoKidx– CiscoKidx2015年07月25日 22:53:22 +00:00Commented Jul 25, 2015 at 22:53
-
My one question would be is there a way to make it return a single true or false as opposed to one for each loopCiscoKidx– CiscoKidx2015年07月25日 23:05:31 +00:00Commented Jul 25, 2015 at 23:05
-
The function actually does return a single
true
orfalse
value. That's because it will only return if theif
statement conditional is met, or if the loop is over.heartyporridge– heartyporridge2015年07月25日 23:08:27 +00:00Commented Jul 25, 2015 at 23:08 -
It returns one true or false for your exmaple but in my array I have 300 people it it. It checks each one and returns a true or false.CiscoKidx– CiscoKidx2015年07月25日 23:10:10 +00:00Commented Jul 25, 2015 at 23:10
personExists
from anywere outside that function.var check = personExists([{Name: 'Joe Panik'}]);
is dead code, it is preceded by areturn
statement, You will certainly benefit by formatting your code, and by using meaninful variable names