19

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?

9
  • 1
    Are you iterating over the properties of an object - a {} - or an array - a []?
    – Matt Ball
    Dec 18, 2010 at 15:40
  • 1
    Is there something specific you want to do to the last element? Or is it just a timing thing (when done processing, do x)?
    – dana
    Dec 18, 2010 at 15:41
  • 1
    1- It's not an array, it's an object. 2- I can't do that outside of the loop (which would make things easier) because of the nature of the code (little bit complicated and uses eval, makes me with no control over the executing code)
    – Omar Abid
    Dec 18, 2010 at 15:57
  • 7
    If it is an object, the order of the elements is not guaranteed, ergo there is no "last" element Dec 18, 2010 at 16:00
  • 1
    What I mean is that the last element may vary form one iteration to another (this does not happen in major browsers but the ECMA spec specifically says not to rely on object key order), and your function will yield different values every time Dec 18, 2010 at 16:04

5 Answers 5

22

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

1
  • there is a little type at .map((key, i) => [key, i === length - 1])) the last round parenthesis is too much and can be removed : map((key, i) => [key, i === length - 1])
    – megloff
    Oct 28, 2023 at 13:43
4

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.

4
  • 1
    You should declare variable el with the var statement as well and then you can leave the extra prev variable.
    – viam0Zah
    Dec 18, 2010 at 15:42
  • @Török As given in the question, OP wanted to process the last element separately. The code from your link will process it twice, once within for and once after the }. Dec 18, 2010 at 19:17
  • @icyrock.com: okay. For me, according to the original example, it seems he wants extra processing for the last element. For that case, it works.
    – viam0Zah
    Dec 18, 2010 at 20:22
  • 1
    If the object is empty it will still call 'doSomething(prev);' at the end and you have not set prev yet !!! better to surround the last 'doSomething' with something to check if 'prev' has been set (if not skip!).
    – KXL
    Jun 12, 2014 at 18:41
0

If the keys are not numerical, this works:

let anObject = {'one': 1, 'two': 2, 'three': 3, 'lastKey': 4};
let objectKeys = Object.keys(anObject);
let lastObjectKey = objectKeys.slice(-1).toString();
console.log(lastObjectKey); // 'lastKey'

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

Example with numerical keys causing reordering:

let anObject2 = {3: 3, 2: 2, 'notLastKey': 4, 1: 'lastKey'};
let objectKeys2 = Object.keys(anObject2);
console.log(objectKeys2); // ["1", "2", "3", "notLastKey"]
let lastObjectKey2 = objectKeys2.slice(-1).toString();
console.log(lastObjectKey2); // "notLastKey"

-4

Note that this will only work if the object you are iterating over is an array (has numeric keys)

var a = [1,2,3,4,5];

for (i in a) {
  if(a[+i+1] === undefined) 
    console.log('the last one is: ' + a[i]);
}

Note that the + sign before i is necessary since if omitted, it will do a string concatenation, the keys resulting in 01, 12, 23, etc

5
  • that's correct... but again, we don't know what the OP is iterating over. If it's an array, this is the best way of doing it (the alternative makes my eyes hurt) Dec 18, 2010 at 15:57
  • It fails if given var a = [1, 2, undefined, 4, 5];.
    – viam0Zah
    Dec 18, 2010 at 20:20
  • Object cannot have property names of type Number Dec 19, 2010 at 4:28
  • It also fails if a is a string. Oh, and it also doesn't work if you replace for with while Dec 20, 2010 at 3:22
  • @user205376 try var o = {"1": "one", "2" : "two" } Dec 20, 2010 at 3:23
-4

as said already, there is no distinct order for properties, so last enumerated property is only known afterwards.

var object = { a: 'b', c: 42 };
for ( var string in object ) ;
alert( object[string] );  // last property name is still here 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.