0

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

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • Does this answer your question? [Counting the occurrences / frequency of array elements](https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements) – pilchard Oct 23 '22 at 10:51

1 Answers1

0

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)
}
SamHoque
  • 2,978
  • 2
  • 13
  • 43