How to use Array from() and charCodeAt() method In Javascript
In this approach, Array.from() is a JavaScript method that creates an array from an iterable or array-like object. It’s often used to generate arrays of numbers, characters, or other elements based on specified conditions, making it versatile for data manipulation.
charCodeAt() returns the Unicode of the character whose index is provided to the method as the argument.
Syntax:
Array.from(object, mapFunction, thisValue)
str.charCodeAt(index)
Example: In this example we will generate the numbers and characters in the given range using array from and charCodeAt method.
const startNum = 1;
const endNum = 8;
const numbers = Array.from({ length: endNum - startNum + 1 },
(_, index) => startNum + index);
const startChar = 'A';
const endChar = 'G';
const CharCode1 = startChar.charCodeAt(0);
const CharCode2 = endChar.charCodeAt(0);
const characters = Array.from(
{ length: CharCode2 - CharCode1 + 1 },
(_, index) =>
String.fromCharCode(CharCode1 + index)
);
console.log(numbers);
console.log(characters);
Output
[ 1, 2, 3, 4, 5, 6, 7, 8 ] [ 'A', 'B', 'C', 'D', 'E', 'F', 'G' ]
JavaScript Program to Generate a Range of Numbers and Characters
Generating a range of numbers and characters means creating a sequential series of numerical values or characters, typically within specified start and end points, forming a continuous sequence or collection.
Contact Us