Splitting alphanumeric character for sorting and subsequent concatenation in javascript
I'm trying to sort a bunch of alphanumeric characters that look like this:
[AD850X, MP342X, OP452X, ZC234X, ZC540X]
The sort should only be based on numbers, so I need to remove all alpha characters from this code, and then I want to add those characters after sorting them for my code as before. For example, the above line should look like this:
[850, 342, 452, 234, 540]
Then this,
[234, 342, 452, 540, 850]
And finally, this,
[ZC234X, MP342X, OP452X, ZC540X, AD850X]
I was thinking about how to do this and I am not sure how I would get the same two letters in front to reconnect to the digital code after sorting (the last character, in this case "X", will always be the same and I would bound this value after adding the first two alpha characters as they were before.
If anyone could help me, I would really appreciate it.
Thank!
EDIT: Another question, when this is done, I only want to output the low and high value of the array (which can have different number of elements). I tried to use .min and .max but don't know how to do this with an array that is registered after sorting. So in the above case, I just need "ZC234X" and "AD850X".
source to share
Instead of complicating it by removing the first two letters and then sorting, you can simply sort the array comparing only the matching numbers within each element.
var arr = ['AD850X', 'MP342X', 'OP452X', 'ZC234X', 'ZC540X'],
res = arr.sort((a,b) => a.match(/\d+/)[0] - b.match(/\d+/)[0]),
min = res[0],
max = res[res.length-1];
console.log("min value: " + min + " | max value: " + max);
source to share
You can use an object as a hash table to store the item and its number, and then sort by the shape values of that object.
var data = ['AD850X', 'MP342X', 'OP452X', 'ZC234X', 'ZC540X'];
var obj = {}
data.forEach(e => obj[e] = e.match(/\d+/)[0])
var result = data.sort((a, b) => obj[a] - obj[b]);
console.log(result)
source to share
You can use only matching numeric values for sorting. Array#sort
works in situ.
This sentence uses the default if the regular expression does not match a number.
var array = ['AD850X', 'MP342X', 'OP452X', 'ZC234X', 'ZC540X'];
array.sort((a, b) => (a.match(/\d+/) || 0) - (b.match(/\d+/) || 0));
console.log('min value', array[0]);
console.log('max value', array[array.length - 1]);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
source to share