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.
Sort array by name with sort()
Strings may not be subtracted, but you can compare them using localeCompare
const res = arr.sort((e1, e2) =>
e1.name.toLowerCase().localeCompare(e2.name.toLowerCase())
);
Sort objects in an array alphabetically based on one property
Using the comment by @gurvinder372 as influence, you should do the following:
myArray.sort(function (a, b) {
var textA = a.name.toUpperCase();
var textB = b.name.toUpperCase();
return textA.localeCompare(textB);
});
How can I sort this array of objects alphabetically in node js?
You can call String#normalize
on both names before comparing them with localeCompare
:
const arr = [
{ id: 1, name: 'TV Samsung MP45', price: 325.9, units: 8 },
{ id: 2, name: 'Ábaco de madera (nuevo modelo)', price: 245.95, units: 15 },
{ id: 3, name: 'impresora Epson', price: 55.9, units: 8 },
{ id: 4, name: 'USB Kingston 16GB', price: 5.95, units: 45 }
];
arr.sort((a, b) => a.name.normalize().localeCompare(b.name.normalize()));
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
Sorting array after firstName and lastName, javascript
Try this;
var currentUsers = [ { firstName: "Bob", lastName: "Bobson"},{ firstName: "Bob", lastName: "Anderson"}, { firstName: "Amy", lastName: "Jackson"}];
var sorted = currentUsers.sort(function(a, b) { var aFirstChar = a.firstName.charAt(0); var bFirstChar = b.firstName.charAt(0); if (aFirstChar > bFirstChar) { return 1; } else if (aFirstChar < bFirstChar) { return -1; } else { var aLastChar = a.lastName.charAt(0); var bLastChar = b.lastName.charAt(0); if (aLastChar > bLastChar) { return 1; } else if (aLastChar < bLastChar) { return -1; } else { return 0; } }});
alert(JSON.stringify(sorted));
Javascript Alphabetically sort and move all doubles to the end of array
You could use sorting with map by using a temporary object with a hash table for the same group array. Take from it the length of the used array as group for sorting.
The sorting happens with the group and index.
The result is mapped with index of the sorted temporary array.
Tge first part generates an array with an index of the original array and their group which is taken from pushing a value into the same group. Actually we need oly the array length after pushing of the group. If more items are in the same group, the items will be sorted later.
[
{
index: 0, // Amy
group: 1
},
{
index: 1, // Amy
group: 2
},
{
index: 2, // Dan
group: 1
},
{
index: 3, // Joe
group: 1
},
{
index: 4, // Joe
group: 2
}
]
The above given array is then sorted by group and index, both ascending.
At the last part, a new array is mapped with the index value of the sorted array.
var array = [{ name: 'Amy' }, { name: 'Amy' }, { name: 'Dan' }, { name: 'Joe' }, { name: 'Joe' }], groups = Object.create(null), result = array // this part is only necessary if the names should be in ascending order // for keeping the given order, remove the part until next comment .sort(function (a, b) { return a.name.localeCompare(b.name); }) // remove until here, if necessary .map(function (a, i) { return { index: i, group: (groups[a.name] = groups[a.name] || []).push(0) }; }) .sort(function (a, b) { return a.group - b.group || a.index - b.index; }) .map(function (o) { return array[o.index]; });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sort JavaScript array of Objects based on one of the object's properties
There are 2 basic ways:
var arr = [{name:"ABC"},{name:"BAC"},{name:"abc"},{name:"bac"}];
arr.sort(function(a,b){
var alc = a.name.toLowerCase(), blc = b.name.toLowerCase();
return alc > blc ? 1 : alc < blc ? -1 : 0;
});
or
arr.sort(function(a,b){
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
Be aware that the 2nd version ignore diacritics, so a
and à
will be sorted as the same letter.
Now the problem with both these ways is that they will not sort uppercase ABC
before lowercase abc
, since it will treat them as the same.
To fix that, you will have to do it like this:
arr.sort(function(a,b){
var alc = a.name.toLowerCase(), blc = b.name.toLowerCase();
return alc > blc ? 1 : alc < blc ? -1 : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});
Again here you could choose to use localeCompare
instead if you don't want diacritics to affect the sorting like this:
arr.sort(function(a,b){
var lccomp = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
return lccomp ? lccomp : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});
You can read more about sort here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Related Topics
Stop Execution of JavaScript Function (Client Side) or Tweak It
Change Url Parameters and Specify Defaults Using JavaScript
How to Synchronize a Sequence of Promises
Constructors in JavaScript Objects
Does React Keep the Order for State Updates
Window.Location.Href and Window.Open () Methods in JavaScript
Remove Objects from Array by Object Property
Firestore Update Single Item in an Array Field
What Is the Correct Terminology for JavaScript Promises
JavaScript Unit Test Tools for Tdd
How to Group by and Sum an Array of Objects
How Is Almost Everything in JavaScript an Object
Persist JavaScript Variables Across Pages
What Does (Function($) {})(Jquery); Mean
Detecting Arrow Key Presses in JavaScript
What Is the Shortest Function for Reading a Cookie by Name in JavaScript