简体   繁体   中英

How to return previous and next element by element from array in JavaScript?

I have an array and i want to return the next and previous elements by a given string. This is the array:

var array = [
      "11111",
      "22222",
      "343245",
      "5455",
      "34999",
      "34555",
    ];

The user inputs a random number, unknown number, and i have to find the next and previous elements based on the user' string.

For example the User writes: 3499 And the return must be Previous element is 5455 and next element is 34555.

Use Array#indexOf method to get the index of the element and get other element based on the index.

 var array = [ "11111", "22222", "343245", "5455", "34999", "34555", ]; var ele = "34999"; var index = array.indexOf(ele); console.log('next', array[index + 1]) console.log('prev', array[index - 1])

Using "indexOf":

function getNextIten(num, nums){
    const idx = nums.indexOf(num)
    if (idx && idx < nums.length-1){
        return nums[idx+1]
    }
    return null
}

nums = [5, 3, 7, 8, 1, 10];
num = 7;
console.log(getNextIten(num ,nums)) //8

Or in one line like:

prev = nums.find((_, i, e) => num === e[i + 1]);
next = nums.find((_, i, e) => num === e[i - 1]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM