-3

var people = [{name: "lily", pts: 30}, {name: "harry", pts: 20}, {name: "jennie", pts: 10}];
points.sort(function(a, b){return b.pts - a.pts});

I want to sort everyone in array people by the number of points they have HIGHEST TO LOWEST (descending). is this correct?

7
  • 1
    Does it do what you want? Commented Jun 5, 2019 at 18:26
  • 3
    "is this correct?" Well, have you tried it? Commented Jun 5, 2019 at 18:26
  • 1
    Seems that the code is working. You just want to confirm that is it the correct way to do it. If that's the case then I say it is. Commented Jun 5, 2019 at 18:27
  • 1
    This is not an array of numeric arrays, he wants to sort an array of objects by a numeric field Commented Jun 5, 2019 at 18:29
  • 1
    Your array is people. But you are sorting points. Just change it to: people.sort(....). Other than that, your code should work fine Commented Jun 5, 2019 at 18:31

2 Answers 2

0

Yes it's correct way to sort arrays in JavaScript. You can find more information here.

P.S. you should call sort function on your people array

people.sort(function(a, b){ return a.pts - b.pts; })
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to sort the "People" array, you just need to sort that array, independent of the attr name.

var people = [{name: "lily", pts: 22}, {name: "harry", pts: 20},{name: "jennie", pts: 18}];

The array.prototype.sort function wants to be called in the array.

people.sort(function(a,b){
return a.pts - b.pts })

1 Comment

it would be b.pts-apts as it's higest to lowest

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.