Sort string array with numbers in JavaScript - javascript

I have this array, which I want to sort:
['reactor-sum', 'reactor-sum-23', 'reactor-sum-15', '99', 'reform-match-5', 'reform-match', 'docker-rev']
I want to have it sorted in a way that I have:
1) numbers first
2) sorted alphabetically and if there are numbers in the end of the string - put first the strings without numbers and then the ones with numbers sorted numerically.
Expected result array:
['99',
'docker-rev',
'reactor-sum',
'reactor-sum-15'
'reactor-sum-23',
'reform-match',
'reform-match-5']
So far I tried things like:
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true });
searchResults.sort(sortAlphaNum);
and the regular .sort(), but I can't quite figure out how to achieve what I want.
Anybody have some ideas on how to best sort this array? My biggest issue is with putting the non number strings in front of the ones with numbers like:
[example, example1]

Normal sort() should work out of the box. See this jsFiddle

Related

generate one of the mutiple possibles anagrams of a string

I'm kind of new to JavaSCript and I want to ask wow can I make a random anagram generator, without a list of all possible anagrams (because that's not optimized)
Example:
input: "abc"
output: get the input, split it (["a", "b", "c"]), randomize the split and join them (["cba"])
This is for a command for my bot in Discord.
I've searched about this, but I just found generators for all anagrams possible in the same string.
Thank you for reading this, have a nice day
Well, you've explained it yourself. You just had to search for the commands online...
const input = 'abc';
const output = input
.split('') // make it into strings
.sort(() => 0.5 - Math.random()) // shuffle
.join(''); // convert to a string
Not sure if you need the result to be an array of a single item, or just a string :|
Also, keep in mind the output might be the same as the input! If you don't want this - call the function as many times as needed in order to get a different output.
Edit: as #PA mentioned, using the above-mentioned way to sort arrays is not a great idea. Even though it might currently work, it can lead to bad results. The reason is that the sort algorithm might (not sure) need static values for each item. Theoretically, that might be a problem. Therefore something like this can be used:
const input = 'abc';
const output = input
.split('') // make it into strings
.map((v) => [Math.random(), v]) // convert the array of characters into tuples (pairs)
// of a random element and the real value
.sort((a, b) => a[0] - b[0]) // sort, based on the random values
.map(([rand, value]) => value) // return to list of characters
.join(''); // convert to a single string
This way you set the random value once, then do the shuffling, then remove the random values.

Why alphabetical sorting on numeric inputs? [duplicate]

This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 5 years ago.
Why is this function returning elements sorted alphabetically rather than numerically? I get the identical results whether I use Number or ParseFloat.
function sortMe() {
var x = ["1.0","2.5", "11.0"];
var y = x.map(Number);
Logger.log(y.sort());
}
Result: 1,11,2.5
Because Array#sort sorts alphabetical, so '11' comes before '2'.
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.
To overcome this problem, you could use a numerical sort with a callback, like
array.sort(function (a, b) {
return a - b;
});
That's because the default sort order is according to string Unicode code points, no matter what your input is. Your Number are implicitly converted back to strings and then sorted.
Its not that you are unable to pass a numeric array, whatever you pass Array#sort will try to compare on the basis of their unicode representation. Instead pass a comparator, to compare how you want to compare while sorting
y.sort((a,b)=>a-b)
The sort() method sorts the items of an array.
The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
By default, the sort() method sorts the values as strings in alphabetical and ascending order, with respect to each element's Unicode point value.
Have a look at this example:
var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Note that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
var things = ['word', 'Word', '1 Word', '2 Words'];
things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.

Array sort method unexpected behavior [duplicate]

This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 6 years ago.
I have an array having values are 1,10,6,8,7 and I want to sort this using sort() method, It's giving result like this 1,10,6,7,8 rather than 1,6,7,8,10
I wrote code below :
var arr = [1,10,6,8,7];
arr.sort();
document.write(arr);
Can anyone have idea about this?
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
Refer this link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
10 is before 2 in unicode. You need to help the sort() function to determine which element is before which.
arr.sort(function(a, b) {
return a - b;
});
From the documentation:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order.
This is why sort on an array of number is "weird": because it compares the string representation of the numbers.
In a unicode point of view: "10" < "2".
You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Original answer:
https://stackoverflow.com/a/7000924/7462678
According to the Mozilla Developer Network, "The default sort order is according to string Unicode code points.". 10 comes before 2 in Unicode code point order. You would need to pass in a comparison function to the sort function, which would compare the numbers.
Array.prototype.sort - Mozilla Developer Network

Sorting an array of decimal & whole numbers [duplicate]

This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 8 years ago.
I can't seem to figure this one out.
var arr = [2.62, 111.05, 1.05]
arr.sort();
This returns [1.05, 111.05, 2.62], but I'm expecting [1.05, 2.62, 111.05].
How can this be achieved? I've read a bit about writing a custom sort to split the "decimal" but haven't managed to have any success.
By default sorting is alphabetically. You need to pass a function to the sort method
arr.sort(function(a, b){return a-b;});
The sort method compares the items as strings by default. You can specify a comparer function to make the comparison any way you like. This will compare the items as numbers:
arr.sort(function(a, b){ return a - b; });
Note: All numbers in Javascript a double precision floating point numbers, even if they happen to contain an integer value, so integer values and decimal values are not treated differently.
This is the normal behavior for Array.sort() when it isn't given a comparator function. Try this:
var arr = [2.62, 111.05, 1.05];
arr.sort(function(a,b) { return a-b; });
From MDN:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Cherry" comes before "banana". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.

JavaScript sort array by key?

I have an array with keys like this:
0kefsdfsdf
1101fsdf
55fdsfds
Now I want to sort that array so that the keys start with the smallest number. Afterwards the keys should look like that:
0kefsdfsdf
55fdsf
1101fsdfds
I tried this code, but its not sorting the keys:
myArray.sort(function(a, b) {
return a < b;
});
How can I sort the array according to the keys so that when I iterate the array afterwards, it starts with the key with the lowest number?
You can use
var sorted = myArray.sort(function(a,b){ return parseInt(a,10)-parseInt(b,10) });
This relies on the curious behavior of parseInt which isn't worried when asked to parse "55fdsfds" :
If parseInt encounters a character that is not a numeral in the
specified radix, it ignores it and all succeeding characters and
returns the integer value parsed up to that point. parseInt truncates
numbers to integer values. Leading and trailing spaces are allowed.

Categories

Resources