Created
March 15, 2019 19:36
-
-
Save okovalov/8fc2f7c947df5f2a376740c65e81790e 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
/** | |
Find the minimum value in an array of strings using a loop. For example, for this array: | |
a=['my','name','is','john','doe']; | |
**/ | |
const sortByLengthOnly = arr => arr.sort( (a, b) => a.length - b.length) | |
const sortByLengthAndValue = arr => arr.sort( (a, b) => { | |
if (a.length !== b.length) return a.length - b.length | |
const longer = a.length > b.length ? a : b | |
for (let idx in longer) { | |
if (a[idx] === b[idx]) continue | |
return a[idx] > b[idx] | |
} | |
}) | |
// case one | |
const a = ['my','name','is','john','doe'] | |
const sortedByLengthOnlyA = sortByLengthOnly(a) | |
console.log(`Sorted by length only - ${sortedByLengthOnlyA}`) | |
const sortedByLengthAndValueA = sortByLengthAndValue(a) | |
console.log(`Sorted by length and values - ${sortedByLengthAndValueA}`) | |
// case 2 - to better demostrate sorting by value | |
const b = ['my','name', 'jakob','is','john', 'jake', 'doe'] | |
const sortedByLengthOnlyB = sortByLengthOnly(b) | |
console.log(`Sorted by length only - ${sortedByLengthOnlyB}`) | |
const sortedByLengthAndValueB = sortByLengthAndValue(b) | |
console.log(`Sorted by length and values - ${sortedByLengthAndValueB}`) | |
/** | |
node v10.15.2 linux/amd64 | |
// case 1 | |
Sorted by length only - my,is,doe,name,john | |
Sorted by length and values - is,my,doe,john,name | |
// case 2 | |
Sorted by length only - my,is,doe,name,john,jake,jakob | |
Sorted by length and values - is,my,doe,jake,john,name,jakob | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment