| Viewed 175 times

How to Sort Words by a String in Javascript?


Create a function that accepts a string as an argument. Find its shortest word(s) and return them as an array sorted alphabetically (if there are multiple shortest words).

1 Answer
Mohammad Qandeel
Answered
17

You can try this function, it is importing an array of texts in addition to the letter you want to filter on

function sortByString(arr, str) {
   return arr.sort(function(a, b) {
   var n1 = str.indexOf(a.charAt(0));
   var n2 = str.indexOf(b.charAt(0));
   return n1 - n2;
  });
}

//Example
sortByString(['ok','hi','hello','z','f'],'z') // ["ok", "hi", "hello", "f", "z"]


Related Questions