2

For example

let obj = {1:"asd",2:"sad"};
obj[-1] = "g" 

the object will be

{1:"asd",2:"sad",-1:"g"}, 

I need that -1 key be from the beginning

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • no, it is not possible, because index like keys are sorted first. – Nina Scholz Oct 13 '19 at 18:14
  • if they are truly sorted than -1 must be the first key, by logic – Vahan Zakaryan Oct 13 '19 at 18:16
  • 4
    You can never rely on key order in an object, it has no defined order according to the spec. Use an array instead – Ayush Gupta Oct 13 '19 at 18:19
  • I have a task, solved it, but negative numbers doesn't work as you see) – Vahan Zakaryan Oct 13 '19 at 18:26
  • 1
    @AyushGupta The ES6 spec *does* [introduce a well defined order](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties). It depends on the environment whether it complies with this spec or not. Not all environments do. – VLAZ Oct 13 '19 at 18:33
  • @VLAZ Also, not all methods of accessing an object do actually use that order. – Bergi Oct 13 '19 at 18:46
  • @Bergi that, too. The order is well-defined but also the excluded methods is defined there. – VLAZ Oct 13 '19 at 18:48

2 Answers2

0

I don't think it is wise to use objects as arrays.

Anyway, -1 is not a valid index keys, that is why it is not sorted as the other integer property names. And you cannot really rely on property order.

What you can do is sort your values by key when you need it:

let obj = {1:"asd",2:"sad"};
obj[-1] = "g"

Object.keys(obj).sort((a,b) => a - b).forEach(key => console.log(key + '   =>   ' + obj[key]));
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19
0

Javascript doesn't behave that way by default. There's a good article here explaining how it does behave.

Javascript property ordering is always chronological unless the property is a positive integer which makes it an array index, and they come first and are ordered. -1 isn't a positive integer. It's a string, so it comes in the order it was added. There's a snippet (below) that confirms the behaviour you're reporting.

let obj = {};
obj["ccccc"]="ccccc";
obj["bbbbb"]="bbbbb";
obj["aaaaa"]="aaaaa";
obj[10]=10;
obj[5]=5;
obj["-2"]=-2;
obj["-3"]=-3;
obj[-22]=22;
obj[0]=0;
console.log(Reflect.ownKeys(obj));
Object.keys(obj).sort().forEach(key => console.log(key))

There are a number of ways to implement the behavior you want, but you won't get it without coding. The easiest way to do that is to simply sort the keys using Object.keys(obj).sort(), but as you can see from the example, by default, does a lexical sort that doesn't really work for numbers. You'd want to then improve that with sort((a,b) => a - b), but that's problematic if you need integers and strings as keys.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102