Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
0.4: JS Object as Tally

Introduction

JS Objects are useful for tallying frequencies of elements in arrays. For example, for a hand of cards, we could use an Object to tally the frequency of each card name. We can use card names as Object keys, and frequencies as Object values. The algorithm to tally card name frequencies works as follows.
  1. 1.
    Initialise an empty JS Object tally.
  2. 2.
    Iterate through the hand array.
  3. 3.
    For each card in the hand array, do the following.
    1. 1.
      If that card's name exists in tally, increment its value by 1.
    2. 2.
      Else, add that card's name as a key in tally with value 1.
This algorithm can be used to tally other card attributes by using those attributes as key names, for example ranks and suits.

Sample Code

See 1.5: High Card DOM for implementations of makeDeck and shuffleCards functions.

Create Tally

1
// Create shuffled deck
2
var deck = shuffleCards(makeDeck());
3
​
4
// Create hand array of 5 cards
5
var hand = [];
6
for (let i = 0; i < 5; i += 1) {
7
hand.push(deck.pop());
8
}
9
​
10
// Create Object as tally
11
var cardNameTally = {};
12
​
13
// Loop over hand
14
for (let i = 0; i < hand.length; i += 1) {
15
var cardName = hand[i].name;
16
// If we have seen the card name before, increment its count
17
if (cardName in cardNameTally) {
18
cardNameTally[cardName] += 1;
19
}
20
// Else, initialise count of this card name to 1
21
else {
22
cardNameTally[cardName] = 1;
23
}
24
}
Copied!

Read Tally

When we wish to analyse the results in the tally, we can loop over the keys and values in the tally as follows. The following code prints out the frequency of each card name.
1
for (cardName in cardNameTally) {
2
console.log(`There are ${cardNameTally[cardName]} ${cardName}s in the hand`);
3
}
Copied!
Last modified 2mo ago