Last active
September 13, 2018 19:48
-
-
Save pixelsnob/a8045f8c701c814656589610cfc13148 to your computer and use it in GitHub Desktop.
Sort an array of strings and numbers, but keeping the position of where strings or numbers appear in the original array
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
const arr = [ | |
'tree', 'zebra', 40, 'y', 5000, 8, 14, 'zzzzz', 1, 'a', 'bbbbb' | |
]; | |
let numbers_pos = []; | |
let words_pos = []; | |
let words_slots = [], numbers_slots = []; | |
arr.forEach((val, i) => { | |
if (typeof val == 'string') { | |
words_pos[i] = val; | |
words_slots.push(i); | |
} else { | |
numbers_pos[i] = val; | |
numbers_slots.push(i); | |
} | |
}); | |
let words = words_pos.filter(val => !!val).sort((a, b) => a.localeCompare(b)); | |
let numbers = numbers_pos.filter(val => !!val).sort((a, b) => a > b ? 1 : (a == b ? 0 : -1)); | |
let sorted = []; | |
words.forEach((word, i) => { | |
let slot = words_slots[i]; | |
sorted[slot] = word; | |
}); | |
numbers.forEach((number, i) => { | |
let slot = numbers_slots[i]; | |
sorted[slot] = number; | |
}); | |
console.log(arr, sorted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment