Mapping array of numbers to an object with corresponding char codes in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of numbers. For each number in the array, we need to create an object. The object key will be the number, as a string. And the value will be the corresponding character code, as a string.

We should finally return an array of the resulting objects.

Example

Following is the code −

 Live Demo

const arr = [67, 84, 98, 112, 56, 71, 82];
const mapToCharCodes = (arr = []) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      const obj = {};
      obj[el] = String.fromCharCode(el);
      res.push(obj);
   };
   return res;
};
console.log(mapToCharCodes(arr));

Output

Following is the console output −

[
   { '67': 'C' },
   { '84': 'T' },
   { '98': 'b' },
   { '112': 'p' },
   { '56': '8' },
   { '71': 'G' },
   { '82': 'R' }
]
raja
Published on 20-Apr-2021 06:23:25
Advertisements