Skip to content

Commit 28c6635

Browse files
committed
Utils.Array.SortByDigits is a new function that takes the given array of strings and runs a numeric sort on it, ignoring any non-digits.
1 parent bba8285 commit 28c6635

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

src/utils/array/SortByDigits.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @author Richard Davey <rich@photonstorm.com>
3+
* @copyright 2020 Photon Storm Ltd.
4+
* @license {@link https://opensource.org/licenses/MIT|MIT License}
5+
*/
6+
7+
/**
8+
* Takes the given array and runs a numeric sort on it, ignoring any non-digits that
9+
* may be in the entries.
10+
*
11+
* You should only run this on arrays containing strings.
12+
*
13+
* @function Phaser.Utils.Array.SortByDigits
14+
* @since 3.50.0
15+
*
16+
* @param {string[]} array - The input array of strings.
17+
*
18+
* @return {string[]} The sorted input array.
19+
*/
20+
var SortByDigits = function (array)
21+
{
22+
var re = /\D/g;
23+
24+
array.sort(function (a, b)
25+
{
26+
return (parseInt(a.replace(re, ''), 10) - parseInt(b.replace(re, ''), 10));
27+
});
28+
29+
return array;
30+
};
31+
32+
module.exports = SortByDigits;

src/utils/array/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ module.exports = {
4040
SendToBack: require('./SendToBack'),
4141
SetAll: require('./SetAll'),
4242
Shuffle: require('./Shuffle'),
43+
SortByDigits: require('./SortByDigits'),
4344
SpliceOne: require('./SpliceOne'),
4445
StableSort: require('./StableSort'),
4546
Swap: require('./Swap')

0 commit comments

Comments
 (0)