rkaartikeyan rkaartikeyan - 10 days ago 8
Javascript Question

How to move to prev/next index key of an array

In this Post How to move to prev/next element of an array its telling how to move prev/next a array ellement.

But i want the same concept for Prev/Next Array Element Key.

Ex:

var arr = new Array();
arr[2] = 'hi';
arr[3] = 'hello';
arr[4] = 'how are you';
arr[12] = 'i am fine';

arr.next(3); // returns 4
arr.next(4); // returns 12
arr.next(2); // returns 3
arr.next(12); // returns 2
arr.prev(2); // returns 12

Answer

Try this:

var arr = new Array();
arr[2] = 'due';
arr[3] = 'hello';
arr[4] = 'quattro';
arr[12] = 'i am fine';

Array.prototype.next = function(n,_k){
    if(typeof this !== "object") return false;
    _k = n;
    n = (typeof n === "undefined" || n+1 == this.length) ? 0 : n + 1;
    for(n; this.length > n+1; n++){
        if(typeof this[n] !== "undefined") return this[n]; // return element value if you want only index use "return n" ... this is for all return
    }
    for(n = 0;n == _k; n++){
        if(typeof this[n] !== "undefined") return this[n];
    }
    return false;
}

Array.prototype.prev = function(n,_k){
    if(typeof this !== "object") return false;
    _k = n;
    n = (typeof n === "undefined" || n == 0) ? this.length : n-1;
    for(n; n > 0; n--){
        if(typeof this[n] !== "undefined") return this[n];
    }
    for(n = 0;n == _k; n--){
        if(typeof this[n] !== "undefined") return this[n];
    }
    return false;
}

var el = arr.next(12);
var el2 = arr.prev(12);

console.log(el);
console.log(el2);

in jsfiddle