Transforming array of numbers to array of alphabets using JavaScript


We are required to write a JavaScript function that takes in an array of numbers. Our function should return a string made of four parts −

  • a four character 'word', made up of the characters derived from the first two and last two numbers in the array. order should be as read left to right (first, second, second last, last),

  • the same as above, post sorting the array into ascending order,

  • the same as above, post sorting the array into descending order,

  • the same as above, post converting the array into ASCII characters and sorting alphabetically.

The four parts should form a single string, each part separated by a hyphen (-).


Following is the code −

 Live Demo

const arr = [99, 98, 97, 96, 81, 82, 82];
const transform = (arr = []) => {
   let res = [];
   res.push(arr[0], arr[1], arr[arr.length-2], arr[arr.length-1]);
   res =>String.fromCharCode(x)).join('');
   const arr1 = arr
   .map(el => String.fromCharCode(el))
   const arr2 = (arr1.slice(0, 2) + ',' + arr1.slice(-2))
   const arr3 = arr2
   return `${res}-${arr2}-${arr3}-${arr2}`;