Computer >> Computer tutorials >  >> Programming >> Javascript

Sorting an array objects by property having null value in JavaScript


We are required to write a JavaScript function that takes in an array of objects. The objects may have some of their keys that are mapped to null.

Our function should sort the array such that all the objects having keys mapped to null are pushed to the end of the array.

Example

The code for this will be −

const arr = [
   {key: 'a', value: 100},
   {key: 'a', value: null},
   {key: 'a', value: 0}
];
const sortNullishValues = (arr = []) => {
   const assignValue = val => {
      if(val === null){
         return Infinity;
      }
      else{
         return val;
      };
   };
   const sorter = (a, b) => {
      return assignValue(a.value) - assignValue(b.value);
   };
   arr.sort(sorter);
}
sortNullishValues(arr);
console.log(arr);

Output

And the output in the console will be −

[
   { key: 'a', value: 0 },
   { key: 'a', value: 100 },
   { key: 'a', value: null }
]