I have an array
var arr = ["1", "3", "2", "4"];
I need a function that returns the next or the previous array key based on a given key value:
function closestTo(arr, key, direction) {
// do stuff here and return the next or previous id
}
So to find next of 4, I call the function; closestTo(arr, 4, 'next' )
this should return 1
And closestTo(arr, 4, 'prev' )
should return 2
Any ideas of this could also achieved with underscore?
I have an array
var arr = ["1", "3", "2", "4"];
I need a function that returns the next or the previous array key based on a given key value:
function closestTo(arr, key, direction) {
// do stuff here and return the next or previous id
}
So to find next of 4, I call the function; closestTo(arr, 4, 'next' )
this should return 1
And closestTo(arr, 4, 'prev' )
should return 2
Any ideas of this could also achieved with underscore?
Share Improve this question edited Feb 8, 2015 at 12:25 numediaweb asked Feb 7, 2015 at 23:57 numediawebnumediaweb 17.1k12 gold badges79 silver badges116 bronze badges 2- For 1 and "prev" it has to be ...? And if the key isn't found? – Andreas Commented Feb 8, 2015 at 0:07
- it has to be 4 :) .. It is like a loop; so always returns something except when the supplied key is not found; inthis case it returns null or false.. .. – numediaweb Commented Feb 8, 2015 at 0:08
3 Answers
Reset to default 4Maybe something like this?
function closestTo(arr, key, direction) {
var offset_index = (direction === 'prev') ? -1 : 1;
// Convert to integers
var intarr = arr.map(function(x) {
return parseInt(x, 10);
});
return intarr[(intarr.length + intarr.indexOf(key) + offset_index) % intarr.length];
}
I have wrote script for you:)
http://jsfiddle/maxim_mazurok/6s7z6zwt/
But array should be like var arr = [1, 2, 3, 4];
if you want to call function with number as a second param.
var arr = [1, 2, 3, 4];
function closestTo(arr, key, direction) {
var last = arr.length - 1;
var first = 0;
var keyIndex = arr.indexOf(key);
switch (direction) {
case ('next'):
if (keyIndex != last) {
return arr[keyIndex + 1];
} else {
return arr[first];
}
break;
case ('prev'):
if (keyIndex != first) {
return arr[keyIndex - 1];
} else {
return arr[last];
}
}
}
alert(closestTo(arr, 4, 'next' ));
alert(closestTo(arr, 4, 'prev' ));
You only need pure JavaScript for this:
function closestTo(arr, key, direction) {
var keyIndex = arr.indexOf(key),
indexToReturn;
if (direction === 'prev') {
indexToReturn = keyIndex > 0 ? keyIndex - 1 : arr.length -1;
} else if (direction === 'next') {
indexToReturn = keyIndex < arr.length - 1 ? keyIndex + 1 : 0;
}
return arr[indexToReturn];
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745610345a4635911.html
评论列表(0条)