
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Transform Array of Numbers to Array of Alphabets Using JavaScript
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 −
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
Advertisements