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?
CodePudding user response:
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;
});
}
CodePudding user response:
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)
CodePudding user response:
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; }
CodePudding user response:
let data = [
'B3', 'B4', 'B5',
'B6', 'C3', 'C4',
'C5', 'C6', 'D3',
'D4', 'D5', 'D6'
];
console.log(data.map(x => [x.match(/[A-Z]/g)[0], parseInt(x.match(/\d /g))]).sort((a, b) => {
return a[1] - b[1] || a[0].localeCompare(b[0]);
}).map(x => x[0] x[1]))
CodePudding user response:
Here is what I came up with:
const sortByNum = arr => {
let newArr = arr.map(item => {
return {
letter: item[0],
number: item.substr(1, item.length),
};
});
newArr.sort((numA, numB) => numA.number - numB.number);
return newArr.map(item => {
return (item.letter item.number);
});
};
its basically dividing each string into key/value pairs, sorting them by number, then joining them back into strings.