Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript forEach() through an array: how to get the previous and next item?

Let's say we have an array of objects like:

var fruits = [ {name:"banana", weight:150},{name:"apple", weight:130},{name:"orange", weight:160},{name:"kiwi", weight:80} ]

I want to iterate through fruits and tell each time the name of the current, the previous and the next fruit. I would do something like:

fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + item[index-1].name);  
console.log("Next: " + item[index-1].name);
});

But obviously it doesn't work for next and previous items... Any idea?

Please note that I do not want to use the classic for loop

(for i=0; i

Thanks a lot!

like image 759
nadir Avatar asked Aug 01 '16 10:08

nadir


2 Answers

Its not working because item is not an array so we cannot write item[index-1].name. Instead, we need to use fruits[index-1] .Also, the first element of the array will not have the previous item and the last element will not have next item. Code snippet below should work for you.

var fruits = [{
    name: "banana",
    weight: 150
}, {
    name: "apple",
    weight: 130
}, {
    name: "orange",
    weight: 160
}, {
    name: "kiwi",
    weight: 80
}]

fruits.forEach(function(item, index) {
    console.log("Current: " + item.name);
    if (index > 0) {
        console.log("Previous: " + fruits[index - 1].name);
    }
    if (index < fruits.length - 1) {
        console.log("Next: " + fruits[index + 1].name);
    }
});
like image 75
Nehal Gala Avatar answered Oct 20 '22 13:10

Nehal Gala


Callback function in ForEach loop accepts the array as third parameter :

fruits.forEach((item, index, arr) => {
    console.log("Current: " + item.name);
    console.log("Previous: " + ((0 === index)? "START" : arr[index-1].name));
    console.log("Next: " + ((arr.length - 1 === index)? "END" : arr[index+1].name));
});
like image 22
kevin ternet Avatar answered Oct 20 '22 12:10

kevin ternet