Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading