我有一个包含一个或多个数组的数组:
例如,有一个数组:
var array1 = [['2','name','surname','2014-01-01']];
或者有多个(它是动态的,有时它带有另外1个带有2个,有3个,......但总是带有订购的日期' asc')。
var array1 = [['2','name','surname','2014-01-01'],['2','name1','surname1','2014-02-02'],['2','name2','surname2','2014-03-03'],['2','name3','surname3','2014-04-02']];
然后我有一个约会:
var givenDate="2014-03-28";
我想得到givenDate在范围内的数组。我想要开头的数组。在这种情况下,第三个数组:['2','name2','surname2','2014-03-03']
我不知道哪种方式最有效。
由于
答案 0 :(得分:-1)
编辑: 这将返回一个与givendate完全匹配的数组。如果没有找到完全匹配,它将返回最接近给定日期的数组:
var array1 = [['2','name','surname','2014-01-01'],['2','name1','surname1','2014-02-02'],['2','name2','surname2','2014-03-03'],['2','name3','surname3','2014-04-02']];
var givenDate = '2014-02-12';
var key = false;
var index;
var differences = [];
for( index=0; index < array1.length; ++index ){
if( array1[index][3] == givenDate ){
key = index;
}
}
if( !key ){
for( index=0; index < array1.length; ++index ){
difference = givenDate.replace(/-/g, '') - array1[index][3].replace(/-/g, '')
differences[difference] = [];
differences[difference]['key'] = index;
}
}
if( key ){
alert( 'Exact match for given date is found and holds key: ' + key );
alert( 'Resulting array: ' + array1[key] );
}
if( differences.length > 0 ){
alert( 'Found a nearest key' );
var firstKey = getFirstKey(differences);
alert( 'Resulting Array: ' + array1[differences[firstKey]['key']] );
}
function getFirstKey( data ) {
for (elem in data )
return elem;
}