How to Find Previous or Next Element from Array in JavaScript

How to find previous or next element from array in Javascript?

You can try this code here:

Description:

  1. item index fine and check your current position in the array.

  2. display the current index.

  3. when prev button click check it's the first item is not an array when isn't condition the decrement one and display the value current item -1.

  4. when you click the next the same condition and it last item or not check here and change the current index and display value increment 2.

in the next button click display increment by 2 at a time, because when current index increment on then it shows increment 2, the main reason is the element increase 1 and index contain is 0. so it's increment by 2 at a time.

if you show after the itemIndex--; then you increment by one.

var arr = [{'id':4},{'id':5},{'id':7},{'id':8},{'id':9}];var  current_id = 5;//find the your current id is exist in the arrayvar itemIndex = arr.map(function(o) { return o.id; }).indexOf(current_id);//display the value of indexdocument.getElementById('display').innerHTML = itemIndex+1;document.getElementById('prev').addEventListener('click', function(e) {  if(itemIndex!=-1 && itemIndex != 0){    document.getElementById('display').innerHTML = itemIndex;    itemIndex--;  }});document.getElementById('next').addEventListener('click', function(e) {  if(itemIndex!==-1 && arr.length-1 > itemIndex){    document.getElementById('display').innerHTML = itemIndex+2;    itemIndex++;    /*document.getElementById('display').innerHTML = itemIndex+1;*/ }});
<div id="display"></div> <button id="prev">prev</button> <button id="next">next</button>

How to get the previous and next elements of an array loop in JavaScript?

as you're talking about "unlimited cycle" I assume your loop is something like that

var i = 0,
l = array.length;

while( true ) // keep looping
{
if(i >= l) i = 0;

// the loop block

if(/* something to cause the loop to end */) break; // <-- this let execution exit the loop immediately

i+=1;
}

The most efficient way to achieve your goal is the naive one: checking

    var previous=array[i==0?array.length-1:i-1];
var current=array[i];
var next=array[i==array.length-1?0:i+1];

obviously cache the length of the array in a variable

var l = array.length;

and (better style) the "vars" out of the cycle

var previuos,
current,
next;

Note that if you are accessing the array read only there would be a faster (but somewhat strange) way:

l = array.length;
array[-1] = array[l-1]; // this is legal
array[l] = array[0];

for(i = 0; i < l; i++)
{
previous = array[i-1];
current = array[i];
next = array[i+1];
}

// restore the array

array.pop();
array[-1] = null;

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

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

How to get next and previous five element of from an array?

const arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
const size = 5
let current = 1

function prev(){
if(current > 1){
current--
let newArr = getNewArr()
console.log(newArr)
}
}

function next(){
if(current >= 1 && current < arr.length/size){
current++
let newArr = getNewArr()
console.log(newArr)
}
}

function getNewArr(){
return arr.slice(size*current - size, size*current)
}
<button onclick=prev()>prev</button>
<button onclick=next()>next</button>

How to move to prev/next element of an array

If you want to keep the list as an Array, you'll have to change its [[prototype]] to make it look like an iterable collection:

Array.prototype.next = function() {
return this[++this.current];
};
Array.prototype.prev = function() {
return this[--this.current];
};
Array.prototype.current = 0;

Now every Array will have the methods prev and next, and the current property, which points to the "current" elements. A caveat: the current property can be modified, thus leading to impredictable results.

Post scriptum: I don't recommend to make prev and next return false when the index is out of range. If you really want to, you can change the methods to something like:

Array.prototype.next = function() {
if (!((this.current + 1) in this)) return false;
return this[++this.current];
};

UPDATE mid-2016

I'm updating this answer because it seems it's still receiving views and votes. I should have clarified that the given answer is a proof of concept and in general extending the prototype of native classes is a bad practice, and should be avoided in production projects.

In particular, it's not much because it's going to mess with for...in cycles - which should always be avoided for arrays and it's definitely a bad practice for iterating through their elements - and also because since IE9 we can reliably do this instead:

Object.defineProperty(Array.prototype, "next", {
value: function() { return this[++this.current]; },
enumerable: false
});

The main problem is that extending native classes is not future-proof, i.e. it may happen that ECMA will introduce a next method for arrays that will probably be incompatible with your implementation. It already happened even with very common JS frameworks - the last case was MooTools' contains array extension which led ECMA to change the name to includes (bad move, IMO, since we already have contains in DOMTokenList objects like Element.classList).

That being said, it's not that you must not extend native prototypes, but you should be aware of what you're doing. The first advice I can give you is to choose names that won't clash with future standard extensions, e.g. myCompanyNext instead of just next. This will cost you some code elegance but will make you sleep sound.

Even better, in this case you can effectively extend the Array class:

function MyTraversableArray() {
if (typeof arguments[0] === "number")
this.length = arguments[0];
else this.push.apply(this, arguments);

this.current = 0;
}
MyTraversableArray.prototype = [];
MyTraversableArray.prototype.constructor = MyTraversableArray;
MyTraversableArray.prototype.next = function() {
return this[++this.current];
};
MyTraversableArray.prototype.prev = function() {
return this[--this.current];
};

In ES6, moreover, it's easier to extend native classes:

class MyTraversableArray extends Array {
next() {
return this[++this.current];
}
}

Alas, transpilers have a hard time with native class extensions, and Babel removed its support. But it's because they can't exactly replicate some behaviours which have no influence in our case, so you can stick with the above old ES3 code.

javascript Get the difference between an element of an array and the previous one

1) You can use old-style for loop with the starting index as 1

const array = [
1633236300000, 1633244100000, 1633248000000, 1633252500000, 1633287600000,
1633291500000,
];

const result = [];
for (let i = 1; i < array.length; ++i) {
result.push(array[i] - array[i - 1]);
}

console.log(result);

get previous item seen in JS for of loop?

You can access the index of the current element. 

var my_fruits = ['apple', 'banana', 'grapes', 'blueberries']
for (const [index,value] of my_fruits.entries()) { if(index) console.log(my_fruits[index-1])}

Delete the previous and next element from an array while using array.map() in javascript

You can first remove the elements and then map the array, here is an example: