Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get prev and next items in array

Tags:

jquery

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?

like image 682
eyalb Avatar asked Mar 23 '10 08:03

eyalb


People also ask

How do you find the next element of an array?

The next() function moves the internal pointer to, and outputs, the next element in the array. Related methods: prev() - moves the internal pointer to, and outputs, the previous element in the array. current() - returns the value of the current element in an array.

What is next() in php?

The PHP next( ) function is used to advance the internal array pointer. It advances the internal array pointer one place forward before returning the element value. This function was introduced in PHP 4.0.

What property of the array can be used when looping?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array. In the loop above, we first initialized the index number so that it begins with 0 .


3 Answers

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];
}
like image 125
Nick Craver Avatar answered Oct 15 '22 00:10

Nick Craver


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.

like image 45
Veger Avatar answered Oct 15 '22 01:10

Veger


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]);
like image 32
jitter Avatar answered Oct 15 '22 01:10

jitter