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

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



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' }
]
Updated on: 2021-04-20T06:24:47+05:30

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements