javascriptstringduplicates

JavaScript duplicates , explain pls


This is a really dumb question, but please help me understand this line of code if (freq[char]). What does it mean? How variable can be in an array without the push() method?

function removeDupl(arg) {
    var answer = "";
    var freq = [];


    for (i = 0; i < arg.length; i++) {
        let char = arg[i]

        if (freq[char]) {       <------- What does it mean ? what condition is that?
            freq[char]++
            console.log("Duplicate:"+ char)

        } else {
            freq[char] = 1

            answer = answer + char
            console.log("not a duplicate:"+char)
        }

    }

    return answer;

}

Solution

  • What does it mean?

    The condition freq[char] is true if the array element at that index exists and has a truthy value. This array only contains numbers; they start at 1 and get incremented for each repetition, so if the element exists it will be truthy (all numbers except 0 and NaN are truthy).

    How variable can be in an array without the push() method?

    You can assign directly to an index. That's done in this code with:

    freq[char] = 1
    

    in the else block.

    So the code loops through the values in the arg array. If the value already exists as an index in the array, the array element is incremented with freq[char]++. Otherwise a new element is created with that index and initialized to 1.

    Note that the message

    console.log("not a duplicate:"+char)
    

    is incorrect. This will be logged the first time any character is encountered. It's unknown at that time whether it's a duplicate or not, it depends on whether there's another occurrence later.