0

I want to sort an array objects like so.

var obj = [{"UMAIR":410},
        {"ALI":2177},   
        {"JOHN":410},
        {"ANTHENY":410},
        {"FRANKLY":410},
        {"FRONTY":534},
        {"SLIM":534},
        {"ASFUND":534}];

I want to sort it with integer values of each object. I am trying to understand following code (that I have found online):

 obj.sort(function(a, b) {
    return a.price - b.price;
});

But in this code its using price property, but I dont' have any specific property here.

2
  • Is that the starting or ending object? What have you tried and what was the problem? Commented Dec 17, 2016 at 23:47
  • 2
    While it is possible to find "the value of the only property", it would likely be a more useful approach overall to fix the initial data-structure. Either use a 'tuple' such as [["JOHN", 123], ..] (eg. the 2nd component is always the value) or an object structure with fixed keys as in [{name: "JOHN", price: 123}, ..]. Commented Dec 17, 2016 at 23:52

1 Answer 1

2

You can try the sort function...

obj.sort(function(a,b) {
   return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
});

is Equivalent to:

obj.sort(function(a,b) {
   var aValue = a[Object.keys(a)[0]];
   var bValue = b[Object.keys(b)[0]];
   if (aValue > bValue)
     return 1;
   else if (aValue < bValue)
     return -1;
   else
     return 0;
}); 

Edit, Just saw your edit, yeah you did find it. You should also search how to extract elements from json, which in your case is Object.keys,

It Returns an array with the key strings.

Since your Object contains a SINGLE key, you get from the array the first value (0) and then, you are making the subtraction of values from a to b.

a,b are entries of your array. they are objects.

In this Link you can check how sorting function works

Code from the Link i provided

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if we want to do it in descending order?
You invert the a and b. Have you checked the link i provided for you?

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.