- 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 objects by property having null value in JavaScript
We are required to write a JavaScript function that takes in an array of objects. The objects may have some of their keys that are mapped to null.
Our function should sort the array such that all the objects having keys mapped to null are pushed to the end of the array.
Example
The code for this will be −
const arr = [ {key: 'a', value: 100}, {key: 'a', value: null}, {key: 'a', value: 0} ]; const sortNullishValues = (arr = []) => { const assignValue = val => { if(val === null){ return Infinity; } else{ return val; }; }; const sorter = (a, b) => { return assignValue(a.value) - assignValue(b.value); }; arr.sort(sorter); } sortNullishValues(arr); console.log(arr);
Output
And the output in the console will be −
[ { key: 'a', value: 0 }, { key: 'a', value: 100 }, { key: 'a', value: null } ]
- Related Articles
- Sorting an array object by property having falsy value - JavaScript
- Sorting an array of objects by property values - JavaScript
- Sorting an array of objects by an array JavaScript
- Sort array of objects by string property value - JavaScript
- Sort array of objects by string property value in JavaScript
- Sorting an array by date in JavaScript
- Sorting an array by price in JavaScript
- Sorting binary string having an even decimal value using JavaScript
- Sorting objects by numeric values - JavaScript
- Retrieve property value selectively from array of objects in JavaScript
- Filter array of objects by a specific property in JavaScript?
- JavaScript array sorting by level
- JavaScript Count the number of unique elements in an array of objects by an object property?
- Sorting array of strings having year and month in JavaScript
- Group objects by property in JavaScript

Advertisements