Skip to content

Instantly share code, notes, and snippets.

@codepo8
Created July 11, 2024 13:30
Show Gist options
  • Save codepo8/7ec7659e62e53f5b9088fe0df38f20c9 to your computer and use it in GitHub Desktop.
Save codepo8/7ec7659e62e53f5b9088fe0df38f20c9 to your computer and use it in GitHub Desktop.
Quick code challenge - sorting on four

How do you sort a list of words on the 4th character of the word? What"s the shortest solution?

[ "strawberry", "helicopter", "wales", "acorn" ]

should be:

[ "strawberry", "wales", "helicopter", "acorn" ]
// str_a_berry, wal_e_s, hel_i_copter, aco_r_n

You can use this dataset to test.

@gangsthub
Copy link

gangsthub commented Jul 11, 2024

Something along the lines:

arr.sort((a, b) => {
  if (a?.[3] && b?.[3]) return a[3].localeCompare(b[3])

  return a.localeCompare(b)
})

What happens when the word is smaller than 4 characters? I'm using a regular sort method, but I'll leave that to you because I don't know your exact requirements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment