Transforming array of numbers to array of alphabets using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

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 (-).

Example

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 = res.map(x=>String.fromCharCode(x)).join('');
   const arr1 = arr
   .map(el => String.fromCharCode(el))
   .sort();
   const arr2 = (arr1.slice(0, 2) + ',' + arr1.slice(-2))
   .split(',')
   .join('');
   const arr3 = arr2
   .split('')
   .reverse()
   .join('');
   return `${res}-${arr2}-${arr3}-${arr2}`;
};
console.log(transform(arr));

Output

cbRR-QRbc-cbRQ-QRbc
raja
Published on 17-Apr-2021 12:55:40
Advertisements