0

I am trying to order an array. I tried following code:

var groupUserCounter=[];
groupUserCounter["g1"]=1;
groupUserCounter["g2"]=2;
groupUserCounter["g3"]=3;

console.log(groupUserCounter.sort(function(a, b){return b-a}));

It returned:

Array [  ]

How can I do descending order?

8
  • 1
    You've added some properties to your array object. Array Indices should be numbers. Commented Aug 14, 2015 at 9:41
  • What do you suggest? I can't remove properties Commented Aug 14, 2015 at 9:42
  • 1
    groupUserCounter.push() instead of assigning the properties. Commented Aug 14, 2015 at 9:42
  • I need key-value arrays. Push doesn't enough for me. Commented Aug 14, 2015 at 9:43
  • How is that? Those properties are not sortable. Please read how JS arrays work. If you need key-value pairs, you have to use an object. That's not sortable though. Commented Aug 14, 2015 at 9:44

1 Answer 1

5

Your issue is that you're trying to mix arrays and objects in a way they don't work. Try pushing objects into an array like this:

var groupUserCounter = [];
groupUserCounter.push({'g1':1});
groupUserCounter.push({'g2':2});
groupUserCounter.push({'g3':3});
groupUserCounter.sort(function(a, b){
    var propA = Object.keys(a)[0],
        propB = Object.keys(b)[0];
    return b[propB] - a[propA];
});

Or just use an object altogether and write a sort function based around Object.keys(yourKeyValueObject) as RGraham kindly demonstrates below.

Sign up to request clarification or add additional context in comments.

1 Comment

It pushes objects (key/value pair) to an array, so you can use the sort function of arrays. It then checks the first property of each object in the array and returns the difference between the value of the property in b and the property in a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.