i have this array
var arr = [
{
name:'Andrej',
price:5
},
{
name:'Andrej',
price: 12
},
{
name:'Don',
price: 12
},
{
name:'Andrej',
price: 2
},
{
name:'Cilia',
price: 40
},
{
name:'Andrej',
price: 10
},
]
so if i want to sort this array by name i will do
var sorted = arr.sort((a,b) => {
return a.name > b.name ? 1 : -1;
})
and now i have th e array sorted by name
if i try
var sorted = arr.sort((a,b) => {
return a.name > b.name;
})
it will not work. It needs 1 and -1 as numbers so the sort function will know how to swap the values.
If i need to sort the array by name and price and i try
var sorted = arr.sort((a,b) => {
return a.name > b.name || a.price - b.price;
})
now my array is sorted by name and price
Why in this case the shortcut works a.name > b.name
but in previous case
when i had just the name it does not work