create array for each letter

by trentHarlem

HTML

<input type="text" id ='wordIN'>
<button onclick="getWordfromInput()">
count characters
</button>
<div id='display'>

</div>

CSS

body {
  font: 1.1em system-ui;
  background-color: dodgerblue;
}

JavaScript

const display = document.getElementById('display')

function getWordfromInput() {
  if (document.getElementById('wordIN').value) {
    const input = document.getElementById('wordIN').value
    display.innerHTML += `<p>You entered:${input}</p>`
    const occurrences = characterCounter(input)
    const myArr = Object.entries(occurrences)
    //const displayArray = myArr.entries()
    console.log()
    display.innerHTML += `${(myArr)}`
    document.getElementById('wordIN').value = '';
  } else {
    console.log('pfft')
  }
}

//const word = 'eeeeeee';
//const word = 'intelligence';
//const word = 'occurrences';
/* display.innerHTML += `<p> word input:</br>
${word}</p>` */

// commented character counter function 

// function input string
function characterCounter(str) {
  // convert string to array
  let arr = str.split('');
  // reduce array to object
  // key: value === unique letter: number of occurrences 

  return arr.reduce((occurrences, letter) => {
    // 'occurrences' is the accumulator in our reduce function and with the initial value set to object {}. The object 'accumulates' properties each iteration.
    // the value of the property(letter count) is then increased by 1 if it exists or set to 1 if it does not.

    occurrences[letter] = occurrences[letter] ? (occurrences[letter] + 1) : 1;
    // 'letter' is the current item of the array iterator.
    // the ternary operator reads like:
    // does our occurrences object already contain this [letter] ?
    // if so, add 1 to its current value 
    // if not set its value to 1
    console.log('occurrences', occurrences)
    console.log('letter', letter)
    // adding these console logs helps visualize the reduce function build the obect through each iteration based on these rules
    return occurrences;
    // outputing an object instead of an array avoids numeric indexing and makes this immediate comparison possible. the letters are the keys, the amount of times they appear in the loop is the value
  },...