Last active
January 29, 2018 07:06
-
-
Save valarpirai/23f4fec6524c7395c00f69f4efa2e54b to your computer and use it in GitHub Desktop.
Character counting in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// FIRST METHOD | |
// Count using array | |
arr = new Array(26).fill(0); | |
s = "ABCAZZ" // Input String | |
for (var i = 0; i < s.length; i++) { | |
var index = s.charCodeAt(i) - 'A'.charCodeAt(0); | |
arr[index] += 1; | |
} | |
console.log(arr) // Output | |
// SECOND METHOD | |
// Count using object or hashmap | |
arr = {}; | |
s = "ABCAZZ" // Input String | |
for (var i = 0; i < s.length; i++) { | |
if (arr[s.charAt(i)]) | |
arr[s.charAt(i)] += 1 | |
else | |
arr[s.charAt(i)] = 1; | |
} | |
console.log(arr) // Output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment