-1

I have an associative array with keys as strings. Now I want to sort them by value descending.

This is the expected result:

[orange: 3, apple: 2,  banana: 1]

But with:

    var arr = [];
    arr["apple"] = 2;
    arr["orange"] = 3;
    arr["banana"] = 1;

    arr.sort(function(a,b) {
        return a.val - b.val;
    });

I get the initial order:

[apple: 2, orange: 3, banana: 1]
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • As Oriol said, you're treating the array as an object. With few exceptions, [everything in JavaScript acts like an object](http://bonsaiden.github.io/JavaScript-Garden/#object.general), and using square bracket notation with strings instead of indices is just a way of defining named properties on an object. If you need to retrieve the values in an order based on their property names, you can play with the [`Object.keys` collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), sort it and loop through it to access your values. – Thriggle Mar 02 '16 at 19:48

1 Answers1

0

In JS, the keys of an array should be non-negative integers.

If you use other keys, you are treating the array as a plain object, not as an array:

var arr = [];
arr.apple = 2;
arr.length; // 0 -- array methods will ignore your property

Since you are not using the special behavior of arrays, you should use a plain object instead:

var arr = {
  apple: 2,
  orange: 3,
  banana: 1
};

However, the properties of an object are not ordered. So sorting them makes no sense.

To bypass this restriction you could use an array of objects, e.g.

var arr = [
  {key: "apple", value: 2},
  {key: "orange", value: 3},
  {key: "banana", value: 1}
];

Then you will be able to sort these objects as explained in Sort array of objects by string property value in JavaScript

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513