indexOf is a built-in method in Javascript for checking the index (position) of an item in array. This method is often use for checking an item availability in array, if item do not exist it returns -1 otherwise the index number of item. This method always return -1 when object is passed in method, either object exist or not.
To check object, the recommended way is to check a unique value in the object.
To check object, the recommended way is to check a unique value in the object.
var someArray=['a','b','c','d'];
console.log(someArray.indexOf('a')) // 0
console.log(someArray.indexOf('b')) // 1
console.log(someArray.indexOf('c')) // 2
console.log(someArray.indexOf('d')) // 3
console.log(someArray.indexOf('e')) // -1
Above code illustrates a normal behaviour of indexOf method. Objects in array reacts differently. Here is the code:
var someObject={'a':'b','c':'d'}
var anotherObject={'a':'b','c':'d'}
var someArray=['a','b','c','d',someObject,anotherObject];
for(var i=0;i < someArray.length;i++){
console.log(someArray[i]);
}
// a
// b
// c
// d
// {a: "b", c: "d"}
// {a: "b", c: "d"}
Above code displays that two objects are present in array. If we just pass them in this method it will return -1.
console.log(someArray.indexOf({'a':'b','c':'d'})); // -1
Putting the object as variable returns the correct index number.
console.log(someArray.indexOf(someObject)); // 4
A function that can loop through array and find a unique property and value in object, then return index number if exist otherwise -1.
var someArray = ['a', 'b', 'c', 'd',{a: "b", c: "d"}];
function isExist(anyArray, propName, valName) {
for (var i = 0; i < anyArray.length; i++) {
if (anyArray[i][propName] == valName) {
return i;
}
}
return -1;
}
console.log(isExist(someArray, 'a', 'b')); // 4
Since now this is only way I found, got any other? drop me in comments.
Post A Comment:
0 comments: