tags:

views:

50

answers:

3

i have an array of numbers

var projects = [ 645,629,648 ];

and a number 645

i need to get the next(629) and prev(648) numbers?

can i do it with jquery?

A: 

You can I do not know about jQuery, but it is fairly simple to create something on your own (assuming that you have always unique numbers in your array):

var projects = [ 645,629,648 ];

function next(number)
{
    var index = projects.indexOf(number);
    index++;
    if(index >= projects.length)
        index = 0;

    return projects[index];
}

Calling next() with a project number returns the next project number. Something very similar can be made for the prev() function.

Veger
A: 

You only need to sort the array once afterwards you can just use the code starting from //start

If number is not present nothing is output

var projects = [ 645, 629, 648 ], number = 645, i = -1;
projects.sort(function(a, b) {
    return a > b ? 1 : -1;
});
//start
i = projects.indexOf(number);
if(i > 0)
    alert(projects[i-1]);
if(i < (projects.length - 1) && i >= 0)
    alert(projects[i+1]);
jitter
+2  A: 

You can make it a bit shorter overall using jquery's $.inArray() method with a modulus:

var p = [ 645,629,648 ];
var start = 645;
var next = p[($.inArray(start, p) + 1) % p.length];
var prev = p[($.inArray(start, p) - 1 + p.length) % p.length];

Or, function based:

function nextProject(num) { 
  return p[($.inArray(num, p) + 1) % p.length]; 
}
function prevProject(num) { 
  return p[($.inArray(num, p) - 1 + p.length) % p.length];
}
Nick Craver
What is the advantage of using `$.inArray()` compared to `indexOf()`, I cannot see any different behavior when looking at the provided documentation? (Just curious as I'd like to learn new things)
Veger
@Veger - I guess since some browsers didn't support `indexOf` at some point (I'm not sure which), it'll use it internally if present, otherwise it'll loop and find it.
Nick Craver