Sort array by firstname (alphabetically) in JavaScript
Suppose you have an array users
. You may use users.sort
and pass a function that takes two arguments and compare them (comparator)
It should return
- something negative if first argument is less than second (should be placed before the second in resulting array)
- something positive if first argument is greater (should be placed after second one)
- 0 if those two elements are equal.
In our case if two elements are a
and b
we want to compare a.firstname
and b.firstname
Example:
users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
This code is going to work with any type.
Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc. when you compare strings, so you may want to use localeCompare
. See other answers for clarity.
How to sort a javascript array alphabetically with numbers at the end (after letters), and correctly sorting numerically?
You could check if the string starts with a digit and sort the rest by groups.
const array = ['10 FOOT', '45 RPM', '9 VOLT', '910D0', 'AGUA', 'BEAST', 'KEN 5', 'NEMCO'];
array.sort((a, b) => isFinite(a[0]) - isFinite(b[0])
|| a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
);
console.log(array);
Sort Array of numeric & alphabetical elements (Natural Sort)
From http://snipplr.com/view/36012/javascript-natural-sort/ by mrhoo:
Array.prototype.naturalSort= function(){
var a, b, a1, b1, rx=/(\d+)|(\D+)/g, rd=/\d+/;
return this.sort(function(as, bs){
a= String(as).toLowerCase().match(rx);
b= String(bs).toLowerCase().match(rx);
while(a.length && b.length){
a1= a.shift();
b1= b.shift();
if(rd.test(a1) || rd.test(b1)){
if(!rd.test(a1)) return 1;
if(!rd.test(b1)) return -1;
if(a1!= b1) return a1-b1;
}
else if(a1!= b1) return a1> b1? 1: -1;
}
return a.length- b.length;
});
}
Or, from Alphanum: Javascript Natural Sorting Algorithm by Brian Huisman:
Array.prototype.alphanumSort = function(caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z] = [];
var x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z][++y] = "";
n = m;
}
this[z][y] += j;
}
}
this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else return (aa > bb) ? 1 : -1;
}
}
return a.length - b.length;
});
for (var z = 0; z < this.length; z++)
this[z] = this[z].join("");
}
How to sort by Numbers first then Alphabetical
If you have always a single letter, you could sort by the numerical rest and by the first letter.
const
array = ["B3", "D2", "F1", "A9", "D12", "A2", "C1", "Z0", "B1"];
array.sort((a, b) => a.slice(1) - b.slice(1) || a[0].localeCompare(b[0]));
console.log(...array);
How to sort array of objects alphabetically except for numbers?
You was half way, String#localeCompare
accepts an option where you can use a natural sorting with strings.
const
array = [{ name: 'product-2' }, { name: 'product-15' }, { name: 'product-3' }, { name: 'product-10' }];
array.sort((a, b) => a.name.localeCompare(
b.name,
undefined,
{ numeric: true, sensitivity: 'base' }
));
console.log(array);
How to sort an array of integers correctly
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
if( a === Infinity )
return 1;
else if( isNaN(a))
return -1;
else
return a - b;
});
console.log(numArray);
Related Topics
How to Correctly Linearize Depth in Opengl Es in Ios
How to Add an In-App Purchase to an iOS Application
How to Crop a Uiimageview to a New Uiimage in 'Aspect Fill' Mode
Library Not Loaded: @Rpath/Fblpromises.Framework/Fblpromises iOS 13.3.1
How to Handle Background Audio Playing While iOS Device Is Locked or on Another Application
How to Use Uiview Autoresizingmask Property Programmatically
Drawing Uibezierpath on Code Generated Uiview
Passing Arguments to Selector in Swift
How to Change Height of Navigation Bar - Swift 3
How to Disable the Uitableview Selection
What Are Sprite Kit'S "Category Mask" and "Collision Mask"
Didregisterforremotenotificationswithdevicetoken Not Called in Ios8, But Didregister...Settings Is
How to Determine If an Annotation Is Inside of Mkpolygonview (Ios)