Search code examples
javascriptarrayssortinglexicographic

How to sort lexicographically array of strings JavaScript


How to sort lexicographically array of e.g. [aa bb cc dd ee] where the you take the first lexicographically smallest name and append it to the lexicographically largest name, Then take the second lexicographically smallest name and append it to the second lexicographically largest name. And if you have odd number of elements like here cc the output i guess should be eeaaccddbb as a whole string. There is no function i found in Mozilla Developer tools for lexicographically array. And if they are even number of elements of array just to return the corresponding concatenations.


Solution

  • Here's something good :p

    function weirdSortConcat(arr) {
      // sort lexicaly by default
      // to be exact sort by char code so digits(0-9) are before maj(A-Z) which are before min(a-z) 
      arr.sort()
      
      let output = ""
    
      // for half of the array
      for (let i = 0; i < Math.floor(arr.length / 2); i++) {
        // take starting at the end then starting by the start
        output += arr[arr.length - i - 1] + arr[i]
      }
      
      // if length is odd add last element to output
      if (arr.length % 2 === 1) {
        output += arr[Math.floor(arr.length / 2)]
      }
      
      return output
    }
    
    console.log(weirdSortConcat(["aa", "bb", "cc"]))
    console.log(weirdSortConcat(["aa", "cc", "bb"]))
    console.log(weirdSortConcat(["aa", "bb", "cc", "dd"]))