

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- 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 an array of objects by an array JavaScript
- Sorting binary string having an even decimal value using JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- JavaScript array sorting by level
- Inserting element at falsy index in an array - JavaScript
- Sorting array of strings having year and month in JavaScript
- Sort array of objects by string property value - JavaScript
- Sorting array of Number by increasing frequency JavaScript
- Flattening an array with truthy/ falsy values without using library functions - JavaScript
- JavaScript Count the number of unique elements in an array of objects by an object property?
- Group by JavaScript Array Object
Advertisements