eyalb
eyalb

Reputation: 3022

get prev and next items in array

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?

Upvotes: 14

Views: 30515

Answers (3)

Veger
Veger

Reputation: 37915

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.

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630559

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];
}

Upvotes: 45

jitter
jitter

Reputation: 54605

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]);

Upvotes: 2

Related Questions