Pushing false objects to bottom in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of objects like this −

const array = [
   {key: 'a', value: false},
   {key: 'a', value: 100},
   {key: 'a', value: null},
   {key: 'a', value: 23}
];

We are required to write a JavaScript function that takes in one such array and places all the objects that have falsy values for the "value" property to the bottom and sorts all other objects in decreasing order by the "value" property.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [
   {key: 'a', value: false},
   {key: 'a', value: 100},
   {key: 'a', value: null},
   {key: 'a', value: 23}
];
const isValFalsy = (obj) => !obj.value && typeof obj.value !== 'number';
const sortFalsy = arr => {
   arr.sort((a, b) => {
      if(isValFalsy(a) && isValFalsy(b)){
         return 0;
      }
      if(isValFalsy(a)){
         return 1;
      };
      if(isValFalsy(b)){
         return -1;
      };
      return b.value - a.value;
   });
};
sortFalsy(arr);
console.log(arr);

Output

The output in the console will be −

[
   { key: 'a', value: 100 },
   { key: 'a', value: 23 },
   { key: 'a', value: false },
   { key: 'a', value: null }
]
raja
Updated on 21-Oct-2020 12:30:28

Advertisements