This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 6 years ago.
If i have an array:
myArray = [['0','Mouse'],['1','Dog'],['2','Cat'],['3','Gerbil']];
How can I alphabetize the array based on the, in this case, animals?
myArray = alpha(myArray);
Results:
myArray = [['2','Cat'],['1','Dog'],['3','Gerbil'],['0','Mouse']];
you can use sort function
var myArray = [['0','Mouse'],['1','Dog'],['2','Cat'],['3','Gerbil']];
console.log(alpha(myArray));
var arr2 = [['5','Mouse'],['0','Mouse'],['1','Dog'],['2','Cat'],['3','Gerbil']];
console.log('another array', alpha(arr2));
function alpha(arr) {
return arr.sort((a, b) => a[1] > b[1]);
}
You could use Array#sort
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
in combination with String#localeCompare
The 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.
var array = [['5', 'Mouse'], ['0', 'Mouse'], ['1', 'Dog'], ['2', 'Cat'], ['3', 'Gerbil']];
array.sort(function (a, b) {
return a[1].localeCompare(b[1]);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 6 months ago.
Given the array of numbers
let el = [25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000];
The output of the following suggests that it ignores the value of 3000
let el = [25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000];
console.log(el.sort());
//Output [10000, 25000, 29000,3000, 33000, 40000,42000, 48000, 54000,57000, 79000, 86000]
So it did sort, but didn't move the 3000 at the 4th position. Why is this happening?
As VLAZ explained, By default, the sort() function sorts values as strings. if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce incorrect results when sorting numbers.
You can fix this by providing a compare function: (a, b) => a - b)
compareFn(a, b) return value
sort order
> 0
sort a after b
< 0
sort a before b
=== 0
keep original order of a and b
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description
e.g.
let el = [25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000];
console.log(el.sort((a, b) => a - b));
This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Sort array of objects by string property value
(57 answers)
Closed 2 years ago.
I have an array of objects like the one below. Although, the order isn't in ascending or descending. Is there function that sorts the numbers in each object and replacing it into a new array or something similar?
let array = [
{
number: 16
},
{
number: 25
},
{
number: 20
},
{
number: 28
}
];
Yes, you can use array.sort() on a copy of your array.
example:
let newArray = [...array].sort((a, b) => a.number - b.number)
That will sort your array ascending.
If you want it descending just switch to b.number - a.number
More info on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
This question already has answers here:
Sorting object property by values
(44 answers)
Closed 4 years ago.
I have an array and I need to sort it in desc order, but it doesn't seem to work. What could I fix?
var array = [];
array['a'] = ['1','2','3'];
array['b'] = ['2','3'];
array['c'] = ['5','6','8','9'];
array.sort(function(a, b) {
return a.length < b.length ? -1 : (a.length > b.length ? 1 : 0);
});
console.log(array);
What could I fix?
Your array is empty, as it doesn't have numeric keys. Therefore sorting it does nothing, when logging you see the non-numeric keys in the array.
As you want fast lookup you need a hashtable (object or Map) however, they are not sorted, so you also need an array to have a sorted order. You could easily build both for your data:
const lookup = {
a: [ '1','2','3'],
b: ['2','3'],
c: ['5','6','8','9'],
};
const sorted = Object.values(lookup).sort((a, b) => a.length - b.length);
console.log(
lookup["a"],
sorted[0]
);
This question already has answers here:
Sort Array Elements (string with numbers), natural sort
(8 answers)
Closed 5 years ago.
We have a bunch of SomeItems which have a field someId which is in the format (simplified / replaced with dummies):
abc.def1.<someNumber>
I have an array of SomeItems and have been sorting it like this:
let rows = someItems.sort((lhs, rhs) => lhs.someId > rhs.someId)
This pretty much just sorts it alphabetically, so this means that the order comes out a little weird:
abc.def1.1
abc.def1.1234
abc.def1.1235
abc.def1.2
abc.def1.234
I instead want it to be numerically sorted - like 1, 2, 234, 1234, etc.
What's a clean way to do this?
You could use String#localeCompare with options.
var array = ['abc.def1.1', 'abc.def1.1234', 'abc.def1.1235', 'abc.def1.2', 'abc.def1.234'];
array.sort(function (a,b) {
return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
});
console.log(array);
This question already has answers here:
How to sort 2 dimensional array by column value?
(14 answers)
Closed 6 years ago.
I need to sort an complex array order by one column of the array.
For example, this array might looks like
array = [["Banana","Chapter3"], ["Orange","Chapter2"], ["Apple","Chapter1"]];
I want it to sort by Chapter, so the result will be
array = ["Apple","Chapter1"],["Orange","Chapter2"],["Banana","Chapter3"]]
But if I do array.sort, it will become
[["Apple","Chapter1"],["Banana","Chapter3"],["Orange","Chapter2"]]
It seems sort by first element's ascii code. How do I sort by specific element in array?
I also created a JSfiddle to illustrate my idea.
You need to pass a comparator to sort:
var array = [["Banana","Chapter3"], ["Orange","Chapter2"], ["Apple","Chapter1"]];
var sorted = array.sort(function (a, b) {
if (a[1] > b[1]) {
return 1;
} else if (a[1] < b[1]) {
return -1;
} else {
return 0;
}
});
console.log(sorted);
// [ [ 'Apple', 'Chapter1' ],
// [ 'Orange', 'Chapter2' ],
// [ 'Banana', 'Chapter3' ] ]