Skip to content

Instantly share code, notes, and snippets.

@MahmoudAgamy
Last active February 13, 2019 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MahmoudAgamy/d726df66a0bd9e48fea269545607c29c to your computer and use it in GitHub Desktop.
Save MahmoudAgamy/d726df66a0bd9e48fea269545607c29c to your computer and use it in GitHub Desktop.
let string = "aabbbcbck"
let strArr = string.split("") // [ 'a', 'a', 'b', 'b', 'b', 'c', 'b', 'c', 'k' ]
// Array to object using For-Loop - counting each letter occurances
let usingForLoop = (arr)=>{
let newObj={};
for(let i=0; i<arr.length; ++i){
newObj[arr[i]] = newObj[arr[i]]+1 || 1;
}
return newObj;
}
console.log("using For Loop: ", usingForLoop(strArr)) //{ a: 2, b: 4, c: 2, k: 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment