Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created March 15, 2019 19:36
Show Gist options
  • Save okovalov/8fc2f7c947df5f2a376740c65e81790e to your computer and use it in GitHub Desktop.
Save okovalov/8fc2f7c947df5f2a376740c65e81790e to your computer and use it in GitHub Desktop.
/**
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