Was it helpful?

Question

Sorting an array object by property having falsy value - 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.

Example

Following is the code −

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

This will produce the following output in console −

[
   { key: 'a', value: 100 },
   { key: 'a', value: 23 },
   { key: 'a', value: false },
   { key: 'a', value: null }
]
raja
Published on 30-Sep-2020 16:58:40
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top