-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountChars.js
62 lines (52 loc) · 1.81 KB
/
countChars.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
How often do the letters in your name repeat?
Write a function that counts how many times each letter of your name
occurs. Your function should take in your first and last name and return
an object where the keys are each character in your name, and the value
is how many times that character appears in your name.
Example input: "Peggy Porth"
Example output: {p: 2, e: 1, g: 2, y: 1, o: 1, r: 1, t: 1, h: 1}
Your function should NOT count spaces and should not be case sensitive (a
lowercase t and a capital T should be considered the same character).
*/
// 1ST WAY -->
// let str = "Angel Donato"
// function countChars(str){
// str = str.toLowerCase().split("").filter((str) => {
// return str.trim() != '';
// });
// // str = str.toLowerCase().split(" ").join("");
// console.log(str);
// let value = 1;
// for(let i = 0 ; i < str.length ; i++){
// for(let j = i + 1 ; j <str.length ; j++){
// if(str[i] === str[j]){
// value++;
// str.splice(j,1);
// j--;
// }
// }
// console.log(`${str[i]} : ${value}`);
// value = 1;
// }
// }
// countChars(str);
// 2ND WAY -->
function countChars(str) {
// initialize a new empty object to hold the letter counte
const count = {};
// remove all spaces and lowercase all characters of the input str
const name = str.toLowerCase().split(" ").join("");
// loop through the letters of the string
for (let i = 0; i < name.length; i++) {
// if the character is not the obj, add it, give it a value of 1
if (!count[name[i]]) {
count[name[i]] = 1;
} else {
// if the character is already in the object, increment that char's value
count[name[i]] += 1;
}
}
return count;
}
console.log(countChars("Mississippi"));