
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
Count Letters in Their Alphabetical Positions for Array of Strings Using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of strings of english lowercase alphabets.
Our function should map the input array to an array whose corresponding elements are the count of the number of characters that had the same 1-based index in the index as their 1-based index in the alphabets.
For instance−
This count for the string ‘akcle’ will be 3 because the characters ‘a’, ‘c’ and ‘e’ have 1-based index of 1, 3 and 5 respectively both in the string and the english alphabets.
Example
Following is the code −
const arr = ["abode","ABc","xyzD"]; const findIndexPairCount = (arr = []) => { const alphabet = 'abcdefghijklmnopqrstuvwxyz' const res = []; for (let i = 0; i < arr.length; i++) { let count = 0; for (let j = 0; j < arr[i].length; j++) { if (arr[i][j].toLowerCase() === alphabet[j]) { count++; } } res.push(count); } return res; }; console.log(findIndexPairCount(arr));
Output
[ 4, 3, 1 ]
Advertisements