How to sort strings in JavaScript
Use String.prototype.localeCompare
a per your example:
list.sort(function (a, b) {
return ('' + a.attr).localeCompare(b.attr);
})
We force a.attr to be a string to avoid exceptions. localeCompare
has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale:
if (item1.attr < item2.attr)
return -1;
if ( item1.attr > item2.attr)
return 1;
return 0;
Sorting strings in descending order in Javascript (Most efficiently)?
If you consider
obj.sort().reverse();
VS
obj.sort((a, b) => (a > b ? -1 : 1))
VS
obj.sort((a, b) => b.localeCompare(a) )
The performance winner is : obj.sort().reverse()
.
Testing with an array of 10.000 elements,
obj.sort().reverse()
is faster thanobj.sort( function )
(except on chrome), andobj.sort( function )
(usinglocalCompare
).
Performance test here :
var results = [[],[],[]]
for(let i = 0; i < 100; i++){
const randomArrayGen = () => Array.from({length: 10000}, () => Math.random().toString(30));
const randomArray = randomArrayGen();
const copyArray = x => x.slice();
obj = copyArray(randomArray);
let t0 = performance.now();
obj.sort().reverse();
let t1 = performance.now();
obj = copyArray(randomArray);
let t2 = performance.now();
obj.sort((a, b) => (a > b ? -1 : 1))
let t3 = performance.now();
obj = copyArray(randomArray);
let t4 = performance.now();
obj.sort((a, b) => b.localeCompare(a))
let t5 = performance.now();
results[0].push(t1 - t0);
results[1].push(t3 - t2);
results[2].push(t5 - t4);
}
const calculateAverage = x => x.reduce((a,b) => a + b) / x.length ;
console.log("obj.sort().reverse(): " + calculateAverage(results[0]));
console.log("obj.sort((a, b) => (a > b ? -1 : 1)): " + calculateAverage(results[1]));
console.log("obj.sort((a, b) => b.localeCompare(a)): " + calculateAverage(results[2]));
Sort a string alphabetically using a function
You can use array sort
function:
var sortAlphabets = function(text) {
return text.split('').sort().join('');
};
STEPS
- Convert
string
toarray
- Sort
array
- Convert back
array
tostring
Demo
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 strings based on a substring JS
You can create a function to extract the last number id using a RegExp combined with String.prototype.match():
Regular expression: /\d+(?=\D*$)/
- \d matches a digit (equivalent to [0-9])
- + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
- Positive Lookahead (?=\D*$)
Assert that the Regex below matches
\D matches any character that's not a digit (equivalent to [^0-9]) - * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
- $ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)
And finally use Array.prototype.sort()
Code:
const arr = ["UserE | 2020", "UserA | 3", "UserB | 0", "UserC | 2", "UserD | 1"]
const getId = s => +s.match(/\d+(?=\D*$)/)[0]
arr.sort((a, b) => getId(a) - getId(b))
console.log(arr)
Sort array of objects by string property value
It's easy enough to write your own comparison function:
function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}
objs.sort( compare );
Or inline (c/o Marco Demaio):
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))
Or simplified for numeric (c/o Andre Figueiredo):
objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort
How sort string with spaces in javascript?
The String.localeCompare
method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order... which is the same as what Array.sort
is supposed to return:
const array = [
{ attributes: { name: "abcd efg" } },
{ attributes: { name: "Übd cd" } },
{ attributes: { name: "Ku cdf" } },
{ attributes: { name: "ab" } }
];
array.sort((a, b) => a.attributes.name.toUpperCase().localeCompare(b.attributes.name.toUpperCase(), "de", { sensitivity: "base" }));
console.log(array);
Related Topics
Display Data Streamed from a Flask View as It Updates
How to Hover in Reactjs? - Onmouseleave Not Registered During Fast Hover Over
Use :Hover to Modify the CSS of Another Class
CSS Transitions Do Not Work When Assigned Trough JavaScript
Is There a Case Insensitive Jquery :Contains Selector
Meaning of "This" in Node.Js Modules and Functions
JavaScript: Object Literal Reference in Own Key'S Function Instead of 'This'
Change the Url in the Browser Without Loading the New Page Using JavaScript
How to Get the Youtube Video Id from a Url
I'Ve Heard Global Variables Are Bad, What Alternative Solution Should I Use
How to Detect When CSS Animations Start and End with JavaScript
How to Fetch the Value of a Non-Standard CSS Property via JavaScript
How to Output Numbers With Leading Zeros in JavaScript
Console.Log() Shows the Changed Value of a Variable Before the Value Actually Changes
State Not Updating When Using React State Hook Within Setinterval