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
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 −
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' }
]Advertisements