Reputation: 119
I'm trying to sort array with custom values, by it's integer value. There is my array:
[ 'a>46', 'a>86', 'h>78' ]
And desired output:
[ 'a>46', 'h>78', 'a>86' ]
Note: the largest possible value to be found in my array is 90.
I'm trying this way:
var newarr = [];
var max = 91;
for (let u = 0; u < array.length; u++) {
var nmbr = parseInt(array[u].replace(/\D/g,'')); // get integer of array element
if (nmbr < max) { // if element is lower than current highest value
max = nmbr;
newarr[0] = array[u]; // assign it to the beggining of new array
} else { // else put it at as the next newarr element
newarr[newarr.lenght+1] = array[u];
}
}
Output:
[ 'a>46', <1 empty item>, 'a>86' ]
Upvotes: 1
Views: 111
Reputation: 9762
I'd recommend using Array.prototype.sort()
.
var array = ["a>46", "h>78", "a>86"]
array.sort(function(a, b) {
var number_a = parseInt(a.replace(/\D/g,''));
var number_b = parseInt(b.replace(/\D/g,''));
return number_a - number_b;
});
Outputs ["a>46", "h>78", "a>86"]
if you wanna learn more about how this actually works I recommend checking out the compare
function example here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Basically: if you return zero, then a
and b
are equal. if you return a negative number that means a
is less than b
. if you return a positive number that means a
is greater than b
.
Upvotes: 2
Reputation: 2161
JavaScript comes with a built in method to sort arrays.
const array = [ 'a>46', 'a>86', 'h>78' ];
array.sort((a, b) => {
a = Number.parseInt(a.replace(/\D/g, ''), 10);
b = Number.parseInt(b.replace(/\D/g, ''), 10);
return a - b;
});
console.log(array);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt
Upvotes: 0
Reputation: 10975
To achieve expected reult, use below option of using array sort function
var array = [ 'a>46', 'a>86', 'h>78' ]
console.log(array.sort((a,b) => a.substring(2) - b.substring(2)));
https://codepen.io/nagasai/pen/eLdYKz?editors=1010
Upvotes: 1