I have an array called Cards that on console log looks like
Array[3]
0: Object
1: Object
2: Object
each of these has a name: which I am using to reference it want to find it reference the obejct I have
var FoundInArray = [];
function CheckIndexArray(ArraySearch, array) {
var i;
for (i = 0; i < array.length; i++) {
if (array[i].name === ArraySearch) {
FoundInArray = array[i];
return true
break
} else {return false;} }
}
if (CheckIndexArray(document.getElementById("userInput").value, Cards) == true) {
console.log(FoundInArray);
the 3 names are ADAM, Arron Shamira, Adrian Omarsh this however only finds ADAM if I search the other two it doesn't find them. The question is why???
-
You are returning false, thats why.Rajesh Dixit– Rajesh Dixit2016年11月01日 10:35:33 +00:00Commented Nov 1, 2016 at 10:35
2 Answers 2
As commented before, your for loop breaks after 1st iteration because of else {return false;}
Also, you can look into Array.find() or Array.filter.
array.find
This will return first matching value or undefined
var arr = [
{name: 'foo', id:1},
{name: 'foo', id:2},
{name: 'bar', id:3},
{name: 'test', id:4}
]
var searchName = "foo";
var r = arr.find(function(x){ return x.name === searchName});
console.log(r)
array.filter
This will return you all matching values or []
var arr = [
{name: 'foo', id:1},
{name: 'foo', id:2},
{name: 'bar', id:3},
{name: 'test', id:4}
]
var searchName = "foo";
var r = arr.filter(function(x){ return x.name === searchName});
console.log(r)
Also if the purpose is only to check the existence of some value, you can even try array.some
Array.some
Unlike previously mentioned methods, this returns a boolean value. If you do not have use for value, you can even use this method.
var arr = [
{name: 'foo', id:1},
{name: 'foo', id:2},
{name: 'bar', id:3},
{name: 'test', id:4}
]
var searchName = "foo";
var isAvailable = arr.some(function(x){ return x.name === searchName});
console.log(isAvailable)
searchName = "foo123";
isAvailable = arr.some(function(x){ return x.name === searchName});
console.log(isAvailable)
1 Comment
the problem is the return false, it breaks the loop.
also there are better ways of filtering an array like array.filter() or array.find()