Searching for duplicates inside an Array

I find this excercice (inside the Alchemy JS course) about how to get the duplicates from a given Array. I found many ways to solve this over stackoverflow but any of them work inside the solving course. Anyway: Can anyone explain how this works?
Thanks again.

–>> the alchemy solving answer was this:

function countElements(elements) {
    let elementCount = {};
    for(let i = 0; i < elements.length; i++) {
        if(!elementCount[elements[i]]) {
              elementCount[elements[i]] = 1;
        } else {
              elementCount[elements[i]] += 1;
        }
    }
    return elementCount;
}

BUT LOOK AT THE TASK:

Write a function countElements that takes in an array and returns an object a count of each element in the array.

const elements = ["e", "k", "e", "z", "i", "z"];
countElements(elements); // returns {e: 2, k: 1, z: 2, i: 1}

guess the pseudo code would sound like this:

  1. create an object // as your storage
  2. iterate over your incoming elements array, one item by one item.
  3. if this item does not exist in your object, create a such property and give it a number 1.
  4. if this item already exists, add the number by 1.

So intresting!! i see. Thanks! So, the logic was to create and introduce each element to the new array and then if they are again sum 1 each time… Its ok but i got trouble trying to reach the example objective {e: 2, k: 1, z: 2, i: 1}. Because this solution just gives the counting for each, Am i right?

Instead of new array, your code is using an new Object. Could you elaborate your trouble more?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.