最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Find next and previous keys in js array - Stack Overflow

matteradmin6PV0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

Maybe 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];
}
Post a comment

comment list (0)

  1. No comments so far