get previous item seen in JS for of loop?

Viewed 4186

in my for element of array loop, I want to access the elements besides the current one. Specifically, the previous or next element. I would also like this to reach across the first/last element barrier. How can this be achieved?

ie. given:

my_fruits = ['apple', 'banana', 'grapes', 'blueberries']

for (const fruit of my_fruits) {
    // When fruit === 'banana', I want to access 'apple', 
    // when fruit === 'blueberries' I want to access 'grapes'.
    // Also when it's the last element, I want to acknowledge that and access the first. 
}

Due to how I'm dealing with async/await in this local, .forEach is something I'd prefer to avoid.

Thanks

6 Answers

You should use forEach loop and use the second parameter which is index.

const arr = ['apple', 'banana', 'grapes', 'blueberries']

arr.forEach((x,i) => {
  let prev = i > 0 ? arr[i - 1] : null;
  let next = i < arr.length ? arr[i + 1] : null;
  
  console.log(`current:${x} next:${next} previous: ${prev}`)
})

If you don't want to use forEach you can use for..in. But besure about this you are not adding any properties other than indexes on the array.

const arr = ['apple', 'banana', 'grapes', 'blueberries']
for(let i in arr){
  console.log(`current:${arr[+i]} next:${arr[+i+1]} previous: ${arr[+i-1]}`)
}

You could use forEach. The third parameter of the callback function is the array. So, you could destructure it to get the [i-1] and [i+1] th items

const my_fruits = ['apple', 'banana', 'grapes', 'blueberries']

my_fruits.forEach((item, i, { [i-1]: prev, [i+1]: next }) => {
  console.log(item, prev, next)
})

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

You can use a regular for (let i = 0; i < len; i++)

let my_fruits = ['apple', 'banana', 'grapes', 'blueberries'];

for (let i = 0, len = my_fruits.length; i < len; i++)
{
    if (i == 0)
    {
        console.log("I am at first iteration. The last item is : "+ my_fruits[len - 1]);
    }
    if (i > 0)
    {
        console.log("I have now : " + my_fruits[i] + " and I have access to " + my_fruits[i - 1]);
    }
    if (i + 1 == len)
    {
        console.log("I am at last iteration. The first item is : "+ my_fruits[i - 1]);
    }
}

I hope that what You need

const my_fruits = ['apple', 'banana', 'grapes', 'blueberries']

for (let fruit in my_fruits) {

  fruit = parseInt(fruit);

   if (! my_fruits[fruit + -1]) {

      console.log(my_fruits[0] + " => " + my_fruits[fruit + my_fruits.length - 1]);

   } else {

      console.log(my_fruits[fruit] + " => " + my_fruits[fruit + -1]);

    }
}

const arr = ['apple', 'banana', 'grapes', 'blueberries']

arr.forEach((x,i) => {
  let prev = i > 0 ? arr[i - 1] : null;
  let next = i + 1 < arr.length ? arr[i + 1] : null;
  
  console.log(`current:${x} next:${next} previous: ${prev}`)
})

I used Maheer Ali's code above, but I had to make a change. I put i + 1 < arr.length instead of i < arr.length because otherwise it always returns true (the index, starting from 0, will always be less than the length of the array, if it exists).

Related