2022-04-08

 08 Apr 2022

Write a Function that Sorts Words by Length in Ascending Order

Taken from Execute Program

Write a function that sorts words by length in ascending order.

We call your sortByLength function on the array, but we don’t use your function’s return value. Instead, your function should modify the array in-place. That’s what JavaScript’s array sort function does, so you don’t need to do anything special! But if you copy the array with a method like slice, sort the copy, and then return the sorted copy, that won’t work.

Solution

This is the answer I came up with:

function sortByLength(words: Array<string>): Array<string> {
  return words.sort((a, b) => a.length - b.length)
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?ssl=3&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABAZzgJygIQJ4BkCmYA5lABYAUA7ugCbIBciAgmmgIbYA8yUaMxAPgCUjFuy48+gxAG8AUIkRp8UEGiTU0dAHSoM5cmwA0iAEZDEAXgGI22gDaESpRAFozDp2SFyAvnLkIBFRHBzgicgUUdCw8L1JtMDYAW3wjKL1YgmIycgBtAHJTUwKTArYKyrZSxAKaepoagogWgoBdHwsAei7EPIAiYv6TfpaIYcR+hpoJ-qrK-ra5IA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated November 7, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems