Last active
November 25, 2020 10:27
-
-
Save TheAthlete/d8b6317eec3a96846a3c8c9654707f4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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