Abhi
Abhi

Reputation: 4261

Sort null values to last in Array of Objects

I have an array of objects as follows:

c = [{a: null}, {a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}]

I want to kind-of sort them by the objects having values first then objects with null.

What I tried is:

c.sort(function(b) { return b.a ? -1 : 1 })

OUTPUT

[{a: 2}, {a: 50}, {a: 1}, {a: 12}, {a: null}, {a: null}]

EXPECTED OUTPUT

[{a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}, {a: null}]

How can I achieve this?

Upvotes: 5

Views: 7030

Answers (8)

Erwan A. R. Riou
Erwan A. R. Riou

Reputation: 403

Here's a case of sorting a Date with null value at the end if exists:

userSortList = users.sort((a, b) => {
    if (b.lastConnectionDate === null || a.lastConnectionDate) {
        return -1
    } else {
        return (
            new Date(b.lastConnectionDate) - new Date(a.lastConnectionDate)
        )
    }
})

Upvotes: 0

georg
georg

Reputation: 214949

This will put nulls and other falsy values to the end of the list:

c = [{a: null}, {a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}];
c.sort((x, y) => !!y.a - !!x.a);

console.log(c);

However, since you don't really sort anything, you can just split the list into two parts an rejoin them:

c = [{a: null}, {a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}];

r = [
  ...c.filter(x => x.a !== null),
  ...c.filter(x => x.a === null)
]

console.log(r)

This also doesn't rely on the sort function being stable.

Upvotes: 7

vsr
vsr

Reputation: 3198

var c = [{
  a: null
}, {
  a: 12
}, {
  a: 1
}, {
  a: 50
}, {
  a: 2
}, {
  a: null
}];

c.sort(function(a, b) {
  return (a.a !== null) ? 0 : 1;
});
console.log(c);

Returning 0 in the sort function will keep the order as it is.

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could test the value. If null, then take the delta of the comparison.

var c = [{ a: null }, { a: 12 }, { a: 1 }, { a: 50 }, { a: 2 }, { a: null }];

c.sort(function (a, b) {
    return (a.a === null) - (b.a === null);
});

console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }

For a stable sort, you could use sorting with map and use the indices as second sort option.

// the array to be sorted
var list = [{ a: null }, { a: 12 }, { a: 1 }, { a: 50 }, { a: 2 }, { a: null }];

// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
    return { index: i, value: el.a === null};
});

// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
    return a.value - b.value || a.index - b.index;
});

// container for the resulting order
var result = mapped.map(function(el){
    return list[el.index];
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Jan Ciołek
Jan Ciołek

Reputation: 1816

It is not perfect but still works,cheers!

var c = [{a: null}, {a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}]

c.sort(function(object1,object2){

  
  if(object1.a === null && object2.a !== null){return 1}
  
  if([object1.a,object2.a].every((a)=>a === null) ||      
     [object1.a,object2.a].every((a)=>a !== null)
     ){return 0}
  
  if(object1.a !== null && object2.a === null){return -1}
  


})

console.log(c);

Upvotes: 0

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

That way ?

c=[{a: null}, {a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}];
c.sort(function(a,b){ return a.a===null ? 1:-1 })
console.log(c);

Edited

Upvotes: 1

prasanth
prasanth

Reputation: 22490

Try with return !a.a - !b.a .valid object goes first

var c = [{a: null}, {a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}];

c.sort(function (a, b) {
    return !a.a - !b.a
});
console.log(c);

Upvotes: 1

Weedoze
Weedoze

Reputation: 13943

const c = [{a: null}, {a: 12}, {a: 1}, {a: 50}, {a: 2}, {a: null}];

let result = [...c.filter(_=>_["a"]!==null),...c.filter(_=>_["a"]===null)];

console.log(result);

Upvotes: 1

Related Questions