Search code examples
javascriptarraysindexingforeachcounting

Array Elements Repetition Counting


What I want to do is to count the amount of each word in array, but my code also adds the index number of element which amount it counts

let array = ['brown', 'apple', 'engine', 'engine', 'engine', 'brown', 'cell', 'Derek']
let shortened = [...new Set(array)].sort()

for (let i = 0; i < shortened.length; i++) {
  array.forEach(element => { if (element === shortened[i]) { count++ } })
  console.log(count)
}

expected output is 1, 2, 1, 1, 3 because asyou see array shortened[] is alphabetically sorted


Solution

  • You need to decline count as a variable inside your for loop, so it resets every time the loop runs.

    let array = ['brown', 'apple', 'engine', 'engine', 'engine', 'brown', 'cell', 'Derek']
    let shortened = [...new Set(array)].sort()
    
    for (let i = 0; i < shortened.length; i++) {
        let count = 0;
        array.forEach(element => {
            if (element === shortened[i]) {
                count++
            }
        })
        console.log(count)
    }