I have an array:
[
'B3', 'B4', 'B5',
'B6', 'C3', 'C4',
'C5', 'C6', 'D3',
'D4', 'D5', 'D6'
]
I need to sort it by the number in each string (in ascending order). The number can be one/double-digit/triple-digit.
Here's what the final array should look like:
[
'B3', 'C3', 'D3',
'B4', 'C4', 'D4',
'B5', 'C5', 'D5',
'B6', 'C6', 'D6'
]
How can I do it?
Assuming that there will always be only one letter at the beginning - then here is the solution:
const input = [
'B3', 'B4', 'B5',
'B6', 'C3', 'C4',
'C5', 'C645', 'D3',
'D4', 'D532', 'D6'
];
console.log(sort(input));
function sort(array) {
return array.sort((a, b) => {
const aVal = parseInt(a.slice(1), 10);
const bVal = parseInt(b.slice(1), 10);
if (aVal < bVal) {
return -1;
}
if (aVal > bVal) {
return 1;
}
return 0;
});
}
You can have a look to the sort method: https://www.w3schools.com/jsref/jsref_sort.asp
And how you can pass a function in for values comparison as a criteria to sort the elements :)
const myArray = [
'B3', 'B4', 'B5',
'B6', 'C3', 'C4',
'C5', 'C6', 'D3',
'D4', 'D5', 'D6'
]
const sortedArray = myArray.sort((a, b) => a[1] - b[1])
console.log(sortedArray)
You can use sort method of array with custom comparator function as:
const arr = [
'B3', 'B4', 'B5',
'B6', 'C3', 'C4',
'C5', 'C6', 'D3',
'D4', 'D5', 'D6',
];
const result = arr.sort((a, b) => +a.match(/\d+/) - +b.match(/\d+/));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }