Skip to content

Instantly share code, notes, and snippets.

@MahmoudAgamy
Last active February 13, 2019 14:51
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/7b98006b609c6d5ffca33593063e04ea to your computer and use it in GitHub Desktop.
Save MahmoudAgamy/7b98006b609c6d5ffca33593063e04ea to your computer and use it in GitHub Desktop.
arrayToObjectUsingReduce
let string = "aabbbcbck"
let strArr = string.split("") // [ 'a', 'a', 'b', 'b', 'b', 'c', 'b', 'c', 'k' ]
// Array to object using reduce - counting each letter occurances
let obj = strArr.reduce((acc,ltr) => {
acc[ltr] = ++acc[ltr] || 1
return acc
},{})
console.log("reduce - object: ", obj) // { 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