javascript newbie here. I was practicing JavaScript30 by Wes Bos, the question was to sort the array by the years in ascending order. This was the answer that he provided:
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 }
];
var age = inventors.sort(function(a,b){
if (a.year>b.year){
return 1;
}else{
return -1;}
});
console.log(age);
Can someone explain to me, how does the return 1
and return -1
work?
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 }
];
var age = inventors.sort(function(a,b){
if (a.year>b.year){
return a;
}else{
return b;}
});
console.log(age);
^ This was the answer I came out with, but it doesn't sort the array based on their years, and im not sure why