Skip to content

Instantly share code, notes, and snippets.

@TheAthlete
Last active November 25, 2020 10:27
Show Gist options
  • Save TheAthlete/d8b6317eec3a96846a3c8c9654707f4d to your computer and use it in GitHub Desktop.
Save TheAthlete/d8b6317eec3a96846a3c8c9654707f4d to your computer and use it in GitHub Desktop.
// Implementation of sorting array that comprises two types of entities.
let arr = [
"Name 1",
"Third",
"First",
"Name 5",
"Fourth",
"Second",
"Name 3",
"Name 10",
];
console.log("Input array:",arr);
function super_sort(array) {
let names = array.filter(item => /[0-9]$/.test(item));
let numbers = array.filter(item => /^[a-z]+$/i.test(item));
console.log("names", names);
console.log("numbers", numbers);
return [...sort_names(names), ...sort_numbers(numbers)];
}
function sort_names(names) {
return names
.map(name => [name, Number(name.match(/[0-9]+$/gi)[0])])
.sort((a, b) => a[1] - b[1])
.map(item => item[0]);
}
function sort_numbers(numbers) {
const order = {
first: 1,
second: 2,
third: 3,
fourth: 4,
};
return numbers
.map(number => [number, order[number.toLowerCase()]])
.sort((a, b) => a[1] - b[1])
.map(item => item[0]);
}
let sorted_arr = super_sort(arr);
console.log("Sorted array:", sorted_arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment