Skip to content
Advertisement

JavaScript: Diference in sorting behavior array of objects with keys by object property

I have two arrays with the same information but different keys.

The keys of the first array are strings:

var myArray=[];

myArray["Bob"]={Name: "Bob", Age:21};
myArray["Steve"]={Name: "Steve", Age:30};
myArray["Tony"]={Name: "Tony", Age:11};

The second array is indexed normally:

var myOtherArray=[];

myOtherArray.push({Name: "Bob", Age:21});
myOtherArray.push({Name: "Steve", Age:30});
myOtherArray.push({Name: "Tony", Age:11});

If I try to sort them by age:

myArray.sort(({Age:b}, {Age:a}) => a-b)
myOtherArray.sort(({Age:b}, {Age:a}) => a-b)

In the end myOtherArray will be sorted but myArray will remain sorted by key. What am I missing here? Thanks!

Advertisement

Answer

Your first array does not actually contain any elements; you are treating it like an object by setting properties on it, which are ordered in insertion order except for numeric keys which are ordered in ascending order.

You used the standard push method to add to the second array, so it works.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement