I have an array like
a=[1,2,3,,4,5];
So now I want to find the missing value index, i.e. 3
, using indexOf
.
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.
To get the index of all occurrences of an element in a JavaScript array: Create an empty array, that will store the indexes. Use a for loop and loop from 0 up to the array's length. For each iteration of the loop, check if the element at that index is equal to the specific element.
Check if the value is undefined
like the following code:
for ( var i = 0; i < a.length; i++ ) {
if ( typeof a[i] === "undefined" ) {
// do stuff here or break the loop
}
}
Update You can do this too:
Array.prototype.indexOfUndefined = function() {
for ( var i = 0; i < this.length; i++ ) {
if ( typeof this[i] === "undefined" ) {
return i;
}
}
}
You need to return i
because i
is the current index, it will search for the first undefined
value.
Demo: http://jsfiddle.net/vdyypq6o/5/
Unfortunately, ES5 Array methods are required* to skip such array holes**, so no indexOf()
or forEach()
will help. ECMAScript 2015 has two new methods called find()
and findIndex()
that could help you, but they are not widely supported yet, so I assume it's not a good answer for this question.
What's left is a good old iteration over indexes:
function findHole(a) {
for (var i = 0; i < a.length; i++) {
// check for only `a[i] === undefined` could be faster,
// but is not enough as it will cause false positives
// when array actually contains `undefined` value
// for example, for `a = [1, undefined, , 2]`,
// correct implementation should return `2`, not `1`
if (a[i] === undefined && !a.hasOwnProperty(i)) {
console.log("Found hole at index " + i);
return i;
}
}
return -1;
}
* — see step 9 in http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.14 for indexOf()
and step 8 http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19 for map()
algorithms that require skipping holes
** — a hole is created in array when there's no value defined for some index, so technically it's not correct to say that a[3]
has null
or undefined
value, because there just isn't any value. But in JavaScript, when we try to get not defined property of some object, what we get is undefined
, that why a[3] === undefined
is true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With