How to Get the Previous Element When Using a for Loop

Get to the previous element in list using for loop [closed]

Instead of doing your for loop like this (which is the preferred way)

for element in list:
do_something()

You can do this:

for i in range(len(list)):
element = list[i]
previous_element = list[i-1]
do_something()

Pay attention that in the first iteration, i will be 0 so list[i-1] will give the last element of the list, not the previous, since there is no previous.

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

Get previous item of ES6 loop

You can save a reference to previous object into a separate variable.

let data = [{name: 'name1'}, {name: 'name2'}, {name: 'name3'}, {name: 'name4'}, {name: 'name5'}];
let prev;for (let item of data){ console.log({current: item.name, previous: prev && prev.name}) prev = item;}

Loop that also accesses previous and next values

This should do the trick.

foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
if obj == foo:
if index > 0:
previous = objects[index - 1]
if index < (l - 1):
next_ = objects[index + 1]

Here's the docs on the enumerate function.

VueJS v-for loop, detect if previous element in object was different? (Change cities, etc)

If i understood you correctly try like following snippet (in computed property first sort your array then loop, compare cities and add empty object before next city):

new Vue({
el: "#demo",
data() {
return {
burgers: [{'city':'LA','store':'Bobs Burgers'},{'city':'Sacramento','store':'Jimmy Burger'},{'city':'LA','store':'Burger King'}, {'city':'NY','store':'Burgers'}]
}
},
computed: {
byCities() {
const arr = this.burgers.sort((a,b) => {
const nameA = a.city.toUpperCase();
const nameB = b.city.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
})
const res = []
for(let i = 0; i < arr.length; i++){
if (i ===0 || arr[i].city !== arr[i-1].city) {
res.push({city: arr[i].city.toUpperCase()})
}
res.push(arr[i])
}
return res
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<li v-for="(burger, i) in byCities" :key="i">
{{ burger.city }} {{ burger.store }}
</li>
</div>


Related Topics



Leave a reply



Submit