Home > Web Front-end > JS Tutorial > body text

Convert numeric array to alphabetic array using JavaScript

WBOY
Release: 2023-08-24 16:53:10
forward
1002 people have browsed it

使用 JavaScript 将数字数组转换为字母数组

Question

We need to write a JavaScript function that accepts an array of numbers. Our function should return a four-part string -

  • A four-character "word" consisting of characters derived from the first two and last two numbers in in the array. The order should be read from left to right (first, second, second last, last),

  • Same as above, sort the array in ascending order,

  • Same as above, sort the array in descending order,

  • Same as above, convert the array to ASCII characters and sort it in alphabetical order.

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

Example

The following is the code -

Live demonstration

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));
Copy after login

Output

cbRR-QRbc-cbRQ-QRbc
Copy after login

The above is the detailed content of Convert numeric array to alphabetic array using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template