Sort By Length

Description


Given an array of strings, sort them in the order of increasing lengths. If two strings have the same length, their relative order must be the same as in the initial array.

Example

For

inputArray = ["abc", "", "aaa", "a", "zz"]

the output should be

sortByLength(inputArray) = ["", "a", "zz", "abc", "aaa"]

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] array.string inputArray

    A non-empty array of strings.

    Guaranteed constraints:
    3 ≤ inputArray.length ≤ 100,
    0 ≤ inputArray[i].length ≤ 100.

  • [output] array.string

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
function sortByLength(inputArray) {
  const copy = inputArray.map((el, i) => [el, i]);
  return copy
    .sort((a, b) =>
      a[0].length !== b[0].length ? a[0].length - b[0].length : a[1] - b[1]
    )
    .map((el) => el[0]);
}