0

Say I have an object that looks like:

{
  0: { ... }
  1: { ... }
  2: { ... }
  ...
  92812093: { ... }
}

If removed some elements throughout this object, how can I keep their relative order? In other words, if between 0 and 3, I removed the key 2, I would want the new keys to be 0, 1, 2, where 0 and 1 were untouched, by 3 has now become 2.

TheRealFakeNews
  • 5,707
  • 13
  • 56
  • 85
  • Perhaps use an object instead of an array... i.e. `var thingy = { "0" : { ... }, "1" : { ... }, "2": { ... } ... "92812093": { ... } }`, You get issues with alpha vs numeric ordering and would have to use "00000000" instead of "0" (etc) – Tibrogargan Apr 23 '17 at 23:52
  • Possible duplicate of [Does JavaScript Guarantee Object Property Order?](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Mikey Apr 23 '17 at 23:57
  • Mikey's comment is correct. Even if one browser stored your object members alphabetically, there's no guarantee the next one will. Using an array seems to do what you want (i..e When you remove element `2`, the element that was `3` is now element `2`). Actually misread your question and thought you were using an array already and wanted element `3` to remain as `3` when `2` was removed. Since you're already using an object that's already the behavior - but your storage order was never guaranteed. – Tibrogargan Apr 24 '17 at 00:04
  • Something is really wrong here if you even need to consider doing this re-indexing. What is the higher level problem you are trying to solve? – charlietfl Apr 24 '17 at 00:15
  • One way to reorder the array would be to filter null values: `array = array.filter( x => x )`. Since you would be creating a new array every time you removed something, this may cause performance issues with large arrays. You're probably better off going with `splice()` as Bernard Lin suggests. – Tibrogargan Apr 24 '17 at 00:19

1 Answers1

1

Unlike arrays, objects do not actually have numerical indices. In other words, there's not even a guarantee that you'll get 0, 1, 2 in that order when you loop through an object.

If order is important, you might choose to take advantage of array indices instead and format your data as var arr = [x, y, z]. This data can be accessed with arr[index]. Using array methods such as pop, shift, or splice to remove elements will ensure that order is preserved.

For example, if we were to splice out arr[1], arr would become [x, z] and z would now be at index 1 instead of index 2.