+ 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?
3 Respuestas
+ 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
0
Can you post the code? Let's see if I can help.
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...