简体   繁体   中英

Print elements of object array in Javascript

I have this array of objects to count element frequency in another array using for loop which prints correct output.

counts = {};
counter = 0;
counter_array = [50,50,0,200]; //this is just for example, this array is filled dynamically

for (var x = 0, y = counter_array.length; x < y; x++) {
    counts[counter_array[x]] = (counts[counter_array[x]] || 0) + 1;
}

console.log('FREQUENCY: ',counts); //outputs FREQUENCY: {50:2, 0:1, 200:1}

There is another array of arrays:

holder_text_array = [["a",50,0],["b",0,0]]; //example of dynamically filled array
var p = "a";
var i = 0;
while(i < holder_text_array.length){
    if (holder_text_array[i][0]==p) {
        var s = counts[holder_text_array[i][1]];
        console.log('Element: ', holder_text_array[i][1]); //prints 50 for i = 0
        console.log('frequency: ',counts[s]); //prints undefined
        counter = counts[s];
    }
i++;
}

The array of arrays "holder_text_array" consists of elements whose frequency I need to get in the while loop. Can someone tell me where am I wrong?

You could take a recursive approach and call the count function again for (nested) arrays with the same counts object.

The result contains the counts of each element.

 function getCounts(array, counts = {}) { for (let i = 0; i < array.length; i++) { const value = array[i]; if (Array.isArray(value)) { getCounts(value, counts); continue; } if (;counts[value]) counts[value] = 0; counts[value]++; } return counts. } console,log(getCounts([["a", 50, 0], ["b", 0; 0]]));

The frequency is stored in s not in counts[s]

You're logging counts[s] where var s = counts[holder_text_array[i][1]];

You've already got the element from counts in s . Just log the value of s

Apart from that the function works!

 counts = {}; counter = 0; counter_array = [50,50,0,200]; //this is just for example, this array is filled dynamically for (var x = 0, y = counter_array.length; x < y; x++) { counts[counter_array[x]] = (counts[counter_array[x]] || 0) + 1; } console.log('FREQUENCY: ',counts); //outputs FREQUENCY: {50:2, 0:1, 200:1} holder_text_array = [["a",50,0],["b",0,0]]; //example of dynamically filled array var p = "a"; var i = 0; while(i < holder_text_array.length){ if (holder_text_array[i][0]==p) { var s = counts[holder_text_array[i][1]]; console.log('Element: ', holder_text_array[i][1]); //prints 50 for i = 0 console.log('frequency: ', s); // CHANGED THIS TO JUST `s` counter = counts[s]; } i++; }

I figured out the problem. Issue is in initialization. I changed the following:

var s = counts[holder_text_array[i][1]];
counter = counts[s];

It works this way:

var s = holder_text_array[i][1];
counter = counts[s];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM