+ 1

Why do I get [object object] in an array of objects after sorting?

I'm using array.sort on an array of objects to sort it according to a key. function sortPlanet(planets){ return planets.sort(function (a,b){ return b.numberOfMoons - a.numberOfMoons;}) } What I get is [[object Object] { name: "Jupiter", numberOfMoons: 63 }, [object Object] { name: "Saturn", numberOfMoons: 60 }, [object Object] { name: "Uranus", numberOfMoons: 27 }, [object Object] { name: "Neptune"....etc. Why? What's with all the [object object] arrays?

16th May 2018, 7:24 PM
Michał Carło
Michał Carło - avatar
3 Antworten
+ 1
// Sorting an object according to its property var data = [ { name: "Jupiter", numberOfMoons: 63 }, { name: "Saturn", numberOfMoons: 60 }, { name: "Uranus", numberOfMoons: 27 }, { name: "Neptune", numberOfMoons: 100 } ]; function sortPlanet(planets){ return planets.sort(function (a,b){ return b.numberOfMoons - a.numberOfMoons;}) } var obj = sortPlanet(data); console.log(JSON.stringify(obj)); https://code.sololearn.com/W6r0xkJ3Ss2A/?ref=app
23rd Jul 2018, 7:41 AM
Calviղ
Calviղ - avatar
0
Can you post the code? Let's see if I can help.
22nd Jul 2018, 11:13 PM
Daniel Cooper
Daniel Cooper - avatar
0
The JS code in the topmost part of the question. I have an array of objects called "planets" and I sort it. I believe the result is either one of the infamous quirks of JS or that of the browser...
23rd Jul 2018, 5:44 AM
Michał Carło
Michał Carło - avatar