Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognize the last iteration in a Javascript object

I have an object that I'm iterating

for (el in object) {
// Some work here
}

I want to know when is the last iteration, inside the iteration, so I can do

for (el in object) {
// Some work here
if (last_iteration) {
// Do something
}
}

Any straightforward way to do it?

like image 832
Omar Abid Avatar asked Dec 18 '10 15:12

Omar Abid


2 Answers

I know I'm late but I just ran into this and fixed it like this:

let i = 0;
const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

for (el in object) {
   const last = i === length - 1; // true if last, false if not last
   console.log(i, el, last);
   i++;
}

Update: A few years later, i++ at the end of a loop really irks me.

const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

for (const [key, isLast] of Object.keys(object)
        .map((key, i) => [key, i === length - 1])) {
    console.log(key, isLast);
}

or

const object = { a: 1, b: 2 };
const length = Object.keys(object).length;

Object.keys(object)
    .map((key, i) => [key, i === length - 1]))
    .map(([key, isLast]) => {
        console.log(key, isLast);
    })

like image 77
Marcel Avatar answered Nov 04 '22 02:11

Marcel


You can do something like this:

var first = true;
var prev;

for (var el in object) {
  // Some work here
  if (first) {
    first = false;
  } else {
    doSomething(prev, object[prev]);
  }
  prev = el;
}

if (prev !== undefined) { // There was at least one element
  doSomethingElse(prev, object[prev]); // Prev is now last of all elements
}

This is in case you want to process all but the last element in one way (doSomething) and process the last element in another way (doSomethingElse).

If you want to process all the elements in one way (doSomething) and want to have extra processing for the last element only (doSomethingExtra), you can do:

var prev;

for (var el in object) {
  // Some work here
  doSomething(el, object[el]);
  prev = el;
}

if (prev !== undefined) { // There was at least one element
  doSomethingExtra(prev, object[prev]); // Prev is now last of all elements
}

To make it even shorter, you can do similar to what Török Gábor did in the gist he provided, by reusing el variable, i.e.:

var el;

for (el in object) {
  // Some work here
  doSomething(el, object[el]);
}

if (el !== undefined) { // There was at least one element
  doSomethingExtra(el, object[el]); // El is now last of all elements
}

Hope this helps.

like image 22
icyrock.com Avatar answered Nov 04 '22 02:11

icyrock.com