How To Sort Array Based On The Numbers In String?
Given this array = [ '3ab1', '2a0', '1abc2' ] How do I sort it to [ '1abc2', '3ab1', '2a0' ] (descending order of the last number) and return [ 1,3,2 ]. (the first numbers of each
Solution 1:
You can use regular expression to get the numbers when using sort
and reduce
to get the result:
var array = [ "22x0", "3x9", "2x1" ];
var reS = /^\d+/, // regexp for getting all digits at the start of the string
reE = /\d+$/; // regexp for getting all digits at the end of the stringvar result = array.sort(function(a, b) { // First: sort the array
a = reE.exec(a); // get the last number from the string a
b = reE.exec(b); // get the last number from the string breturn b - a; // sort in a descending order
}).reduce(function(res, str, i) { // Then: accumulate the result array var gap = reE.exec(array[i - 1]) - reE.exec(str); // calculate the gap between this string str and the last string array[i - 1] (gap = N_of_last_string - N_of_this_string)if(gap > 0) // if there is a gapwhile(--gap) res.push(0); // then fill it with 0s
res.push(+reS.exec(str)); // push this string numberreturn res;
}, []);
console.log("Sorted array:", array); // array is now sortedconsole.log("Result:", result); // result contain the numbers
In recent ECMAScript versions you can do it shortly using arrow functions like this:
let array = [ "22x0", "3x9", "2x1" ];
let reS = /^\d+/,
reE = /\d+$/;
let result = array.sort((a, b) => reE.exec(b) - reE.exec(a))
.reduce((res, str, i) => {
let gap = reE.exec(array[i - 1]) - reE.exec(str);
if(gap > 0)
while(--gap) res.push(0);
res.push(+reS.exec(str));
return res;
}, []);
console.log("Sorted array:", array);
console.log("Result:", result);
Solution 2:
Your question is a bit odd, but you can achieve this using map
and parseInt
:
var arr = [ "1abc2", "3ab1", "2a0" ];
var res = arr.map(function (i) {
returnparseInt(i);
});
console.log(res);
Solution 3:
A combination of sort and map should do the trick.
const ary = [ "1abc2", "3ab1", "2a0" ];
const newarray = ary
.sort((a, b) => {
return a[a.length - 1] < b[b.length - 1];
})
.map((a) => {
returnparseInt(a[0]);
});
console.log(newarray);
Solution 4:
The script below first sorts the array descending, based on the end-numbers, and then returns only the start-numbers of the sorted array.
(I changed your numbers in the array to show that they can be longer than one digit.)
var array = ["31ab12", "20a40", "11abc27"];
array.sort(function(a,b) {
functiongetEndNum(str) {for (var i=str.length-1; i>=0; --i) {if (isNaN(str.charAt(i))) {return str.substring(i+1);}}} //this function returns the end-number of the supplied stringreturngetEndNum(b) - getEndNum(a); //sort array descendingly, based on the end-numbers
});
console.log(array.map(function(a){returnparseInt(a);})); //create a new array with only the start-numbers
Post a Comment for "How To Sort Array Based On The Numbers In String?"