JavaScript – Sort JS Array with Different Data Types
Last Updated :
15 Nov, 2024
Improve
To sort a JS array having different data types we can sort the elements by converting them to similar types, using type-based sorting, or by using external libraries like lodash and underscore.js.
1. Sorting with String Conversion
Convert the elements to strings using String() constructor, and then use JavaScript array.sort() method.
const arr = [30, "JS", true, 10, "CSS", false, 20];
// Convert to strings
const arr1 = arr.map(item => String(item));
arr1.sort();
console.log(arr1);
Output
[ '10', '20', '30', 'CSS', 'JS', 'false', 'true' ]
2. Type Based Sorting
Use custom comparision funciton to sort on the basis of elemen types.
const arr = [30, "JS", true, 10, "CSS", false, 20];
// Write a custom comparison function
function myFunction(a, b) {
const typeA = typeof a;
const typeB = typeof b;
if (typeA === typeB) {
// If same type, compare values directly
return a > b ? 1 : -1;
} else {
// If different types, sort by data type
return typeA > typeB ? 1 : -1;
}
}
arr.sort(myFunction);
console.log(arr);
Output
[ false, true, 10, 20, 30, 'CSS', 'JS' ]
we can also set custom priority order for different types.
const arr = [30, "JS", true, 10, "CSS", false, 20];
// Write a custom comparison function
function myFunction(a, b) {
const typeOrder = ['number', 'string', 'object',
'boolean', 'undefined', 'symbol'];
const typeA = typeof a;
const typeB = typeof b;
if (typeA === typeB) {
// If same type, compare values directly
return a > b ? 1 : -1;
} else {
// If different types, sort by data type
return typeOrder.indexOf(typeA) > typeOrder.indexOf(typeB) ? 1 : -1;
}
}
arr.sort(myFunction);
console.log(arr);
Output
[ 10, 20, 30, 'CSS', 'JS', false, true ]
3. Using Lodash.sortBy() Method
Pass the typeof parameter in _.sortBy() method for type based sorting.
const _ = require('lodash');
const arr = [30, "JS", true, 10, "CSS", false, 20];
const arr1 = _.sortBy(arr, [(item) => typeof item]);
console.log(arr1);
Output
[
true, false, 30,
10, 20, 'JS',
'CSS'
]