I'm trying to sort a list of Objects in ascending order. But there are cases when the sort value is null and in that case, the value should be sorted alphabetically.
I tried to create the following code:
let items = [
{
name: 'Foo',
Km: null
},
{
name: 'Bar',
Km: 4
},
{
name: 'BarFoo',
Km: null
},
{
name: 'FooBar',
Km: 1
},
]
function sortNullValues(values) {
values.sort(function (a, b) {
if(a.Km === null) return 1
if(b.Km === null) return -1
if (a.Km < b.Km) return 1
if (a.Km < b.Km) return -1
if (a.name > b.name) return -1
if (a.name < b.name) return 1
})
return values
}
console.log(sortNullValues(items))
But the null valued objects are not sorting alphabetically. https://jsfiddle.net/am7n61ou/56/
Current Output:
[
{
name: 'Bar',
Km: 4
},
{
name: 'FooBar',
Km: 1
},
{
name: 'Foo',
Km: null
},
{
name: 'BarFoo',
Km: null
}
]
Desired Output:
[
{
name: 'FooBar',
Km: 1
},
{
name: 'Bar',
Km: 4
},
{
name: 'BarFoo',
Km: null
},
{
name: 'Foo',
Km: null
}
]
if(a.Km === null) return 1will catch the case when bothaandbarenull: jsfiddle.net/khrismuc/vyqc1mwf