Here is the code:
var collection = [new Date(2014, 11, 25), new Date(2014, 11, 24)];
var d=new Date(2014, 11, 24);
var idx= collection.indexOf(d);
Two different objects are never equal to each other, even if they have the same properties / values. Here is a forward looking answer to the problem:
ECMAScript 6 introduces Array#findIndex which accepts a comparison callback:
var index = collection.findIndex(function(x) {
return x.valueOf() === d.valueOf();
});
Browser support isn't great yet though.
This is because your "d" object is the different object. In other words:
var d = new Date(2014, 11, 24);
d === new Date(2014, 11, 24); // returns false
You can try this:
var d = new Date(2014, 11, 24);
var collection = [new Date(2014, 11, 25), d];
var idx = collection.indexOf(d); // returns 1
Array.prototype.indexOfDate = function(date){
for (var i = 0; i < this.length; i++){
if (+this[i] === +date) return i;
};
return -1;
};
// then
var idx1 = collection.indexOfDate(d);
indexOf()
won't work here... It's been well explained in the previous answers...
You'd be able to create your own lookup for the index. Here's a simple example comparing the dates using their .getTime()
value...
(function() {
var collection = [new Date(2014, 11, 25), new Date(2014, 11, 24)];
var d = new Date(2014, 11, 24);
var idx1 = -1;
collection.forEach(function(item, index){
if(d.getTime() == item.getTime())
idx1 = index;
});
var intArray = [1, 3, 4, 5];
var idx2 = intArray.indexOf(4);
$('#btnTry1').on('click', function() {
$('#result1').val(idx1);
});
$('#btnTry2').on('click', function() {
$('#result2').val(idx2);
});
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Index:
<input type="text" id="result1" value="">
<button id="btnTry1">Find index in a date array</button>
<br />Index:
<input type="text" id="result2" value="">
<button id="btnTry2">Find index in a regular array</button>
Two Objects will never be equal unless you serialise them. Lucky, Date is pretty easy to serialise as an integer.
var collection = [new Date(2014, 11, 25), new Date(2014, 11, 24)],
d = new Date(2014, 11, 24),
idx;
idx = collection.map(Number).indexOf(+d); // 1
// ^^^^^^^^^^^^ ^ serialisation steps