- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting an array object by property having falsy value - 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 } ]
- Related Articles
- Sorting an array objects by property having null value in JavaScript
- Sorting an array of objects by property values - JavaScript
- Sorting JavaScript object by length of array properties.
- Sorting binary string having an even decimal value using JavaScript
- Sorting an array of objects by an array JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Inserting element at falsy index in an array - JavaScript
- JavaScript array sorting by level
- Sorting array of strings having year and month in JavaScript
- Flattening an array with truthy/ falsy values without using library functions - JavaScript
- Sorting an array that contains the value of some weights using JavaScript
- Sort array of objects by string property value - JavaScript
- JavaScript Count the number of unique elements in an array of objects by an object property?
- Find the number of times a value of an object property occurs in an array with JavaScript?

Advertisements