Skip to content Skip to sidebar Skip to footer

Associate Array / Key Pair Array In Javascript Arranged In With Random Order Of Keys.

Is it possible to have an Associate Array / Key Pair Array arranged in with random order of keys. Whenever, I am adding a new element, javascript is automatically sorting the keys.

Solution 1:

Objects in JavaScript (and your "array" is just an object here) have no inherent order of their properties you can rely on.

As a workaround, you could store the order of keys in a separate array:

var order = [];

a['T1001'] = "B";
order.push( 'T1001' );
a['T1005'] = "A";
order.push( 'T1005' );
a['T1003'] = "C";
order.push( 'T1003' );

If you then traverse the order array, you can get your required order:

for( var i=0; i<order.length; i++ ) {
  console.log( a[ order[i] ] );
}

EDIT

Removing elements from the first list would require the use of indexOf and splice():

functiondelElement( arr, order, index ) {
  // get the position of the element within the ordervar position = order.indexOf( key );

  // delete element from listdelete arr[ order[ pos ] ];

  // remove from ordering array
  order.splice( pos, 1 );
}

Solution 2:

Looks to me as if your using an object. The sorting of an object's properties is never guaranteed. I don't think internet explorer (at least the old versions) sorts the properties but chrome does by default.

Your code is invalid, it should have the properties as strings if they are not numbers. And you would have to use an object

a = {};
a["T1001"] ="B"
a["T1005"] = "A"
a["T1003"] ="C"

You can either use two arrays to store your properties and the value if you want to preserve the ordering, or you cannot guarantee the ordering if you insist on using an object.

Two arrays

a1 = []; a2 = []
a1[0] = "T1001"; a2[0] = "B";
a1[1] = "T1005"; a2[1] = "A";
a1[2] = "T1003"; a2[2] = "C"; 

EDIT: Unless I guessed at what you meant wrong and that T1001, etc are variables containing numbers.

Post a Comment for "Associate Array / Key Pair Array In Javascript Arranged In With Random Order Of Keys."