2

I'm given the task to deduce and explain the lines of codes of a counter program. Below are the codes to the program which is working perfectly. I have included my explanations as comments in the code but it seems my explanation for the last 4 lines of codes (starting from ... "if(counter[index][entry] === undefined){...}") doesn't really explain it. Can anyone please read the codes and give me a better explanation to them especially why we equate "counter[index][entry] = 1".

    <script>      
//an array containing a list of objects with sub arrays that has to be 
//counted "separately"       
var arr = [
{"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":
["ip_cam","ip_other"]},
{"gateways":["v3"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":
["ip_cam"]},
{"gateways":["v2","v3","v4","ccu2"],"manufacturer":
["homematic","intertechno"],"ir":["ir_yes"],"ip":
["ip_cam","ip_other"]},
{"gateways":["v2","ccu1","ccu2"],"manufacturer":["homematic"],"ir":
["ir_yes"],"ip":["ip_cam","ip_other"]},
{"gateways":["gw_none"],"manufacturer":["homematic"],"ir":
["ir_no"],"ip":["ip_cam"]},
{"gateways":["v3","ccu2"],"manufacturer":
["homematic","fs20","intertechno","elro","Eltako Enocean"],"ir":
["ir_yes"],"ip":["ip_cam","ip_other"]},
{"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":
["ir_no"],"ip":["ip_other"]},
{"gateways":["v3","v4"],"manufacturer":["homematic"],"ir":
["ir_no"],"ip":["ip_other"]},
{"gateways":["v2"],"manufacturer":["intertechno"],"ir":["ir_yes"],"ip":
["ip_other"]},
{"gateways":["v4"],"manufacturer":["homematic","intertechno"],"ir":
["ir_yes"],"ip":["ip_cam","ip_other"]}
];  
//console.log(arr.length); 
//first we create an empty array "counter" to contain the separately 
//counted objects

var counter = [];

//we then use "for loop" to loop through the "arr" array to access the 
//first index

for(var i=0; i<arr.length; i++) {
    //console.log(arr[i]);
    // we create a variable "obj" to store the first index object of 
    //the "arr" array and because it is a loop,
    //it will loop till the last object

    var obj = arr[i];
    //so if we console log "obj", it will display the entire indexes in
    //the "arr" array including keys
    //console.log(obj); 

    //we then use "for in" loop to access all the keys in the variable
    // "obj" because we wanna count the number
    //of all respective sub arrays

    for(var index in obj) {
    //so if we console log "index", it will display the entire keys in
    // the "obj" variable; ie:
    //in every object, it will run 4X to access all the keys    
        //console.log(index);            

    //in the next two lines of codes, we have to check if the keys in
    // our counter array already exist because
    //this is where we gonna put or store our counted respective sub 
    //arrays. if it doesn't exit, we create it.

        if(counter[index] === undefined) {
            counter[index] = [];
        }

        //so if we console log "counter[index]", it will show empty 
        //arrays which is gonna contain the respective key counts
        //console.log(counter[index]);

        //next we save the respective arrays to be counted without the
        // keys in a variable "arr2".

        var arr2 = obj[index];             
        //console.log(arr2);

        //now we wanna loop through the "arr2" array because it 
        //contains the entries (in arrays) we wanna count 
        ///starting from the first index to the last

        for(var j = 0; j < arr2.length; j++) {
        //we then store the single entries in a variable called "entry"
        //(not with keys or in an array)

            var entry = arr2[j];
            //console.log(entry);

        //in the next two lines of codes, we have to check if the keys
        //in our counter array exist because this is where
        //we would count "entry"

            if(counter[index][entry] === undefined) {
                counter[index][entry] = 1; 
                //console.log(counter[index][entry]);
            } else {
                counter[index][entry]++;                   
            } 
        }   
    }
}
console.log(counter);
    </script>

2 Answers 2

1

If counter[index][entry] is undefined, it means that we haven't began counting it yet. So we need to start counting it. So we count once, which sets the counter to 1.

If counter[index][entry] does exist (the else clause), it means that there's already a number in counter[index][entry] (because that's what we initialize it to if it doesn't), so just increment the number by one.

Another, perhaps clearer way of writing this would be:

if (counter[index][entry] === undefined) {
    counter[index][entry] = 0; // If it doesn't exist, initialize counter to 0.
}
counter[index][entry]++; // Here the counter is a number for sure, increment once.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Madara, but if we initialize counter = 0, the entry index will be reduced by one, hence example instead of [gateways: v2 to be 3, we will get 2]
No, you won't. Look carefully, I dropped the else clause, so you instantiate it to 0, and then immediately raise it by one.
0

Basically it's trying to count how many each specific property exists. Eg, how many occurences of gateway v2, how many times ip_other exists etc.

The part with 'if(counter[index] === undefined)' is weird. Counter is an array. And index is the key from an object (namely gateway, manufacturer, ip and ir) So basically it's trying to set keys on an array. Although this is valid javascript, counter should be an object instead of an array to be 'more logical'. Hence the code looks a bit confusing.

Anyways, the rest works like madara posted.

2 Comments

Yes i think the more logical way is to use 'key' instead of 'index' and if not how do you expect to make counter an object ?
var counter = {}; Everything else in the code can stay the same, since it's already setting keys on the array, you can continue setting keys on the object. Setting keys on an array is just a slightly bad practice, unless there's a specific reason (like adding metadata) for doing so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.