CASE 1:
let items = [
{ name: "Edward", value: 21 },
{ name: "Shane", value: 37 },
{ name: "Daniel", value: 45 },
{ name: "Daniel", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Magnetic", value: 37 },
];
items.sort(function (a, b) {
if (a.name<b.name) {
return -1;
}
if (a.name>b.name) {
return 1;
}
// names must be equal
return 0;
});
console.log(items);
CASE 2:
let items = [
{ name: "Edward", value: 21 },
{ name: "Shane", value: 37 },
{ name: "Daniel", value: 45 },
{ name: "Daniel", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Magnetic", value: 37 },
];
items.sort(function (a, b) {
if (a.name<b.name) {
return -1;
}
if (a.name>b.name) {
return 1;
}
// no case for equal names
});
console.log(items);
CASE 3:
items.sort(function (a, b) {
return a.name < b.name ? -1 : 1;
});
All three return the following
[
{ name: 'Daniel', value: 45 },
{ name: 'Daniel', value: -12 },
{ name: 'Edward', value: 21 },
{ name: 'Magnetic', value: 13 },
{ name: 'Magnetic', value: 37 },
{ name: 'Shane', value: 37 }
]
All the above mentioned snippets return the same result, but there's definitely some example where all these return different results (Which I don't know). I wanted to know what happens when there's no return condition for the names being equal.
UPDATE: I've added a case 3 to the original question, actually case 1 and case 2 behave similarly because case 2 returns undefined when names are equal. But in case 3 where I use ternary operator it doesn't return undefined but still the answer remains the same. HOW?