
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Array of Objects by Property with Falsy Value in JavaScript
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 } ]
Advertisements