JavaScript Data Structures: Hash Table: Get values
Tags: beginners, tutorial, javascript, webdev
Published: 2020-04-13 17:02:34

---
title: "JavaScript Data Structures: Hash Table: Get values"
description: "JavaScript Data Structures: Hash Table: Get values"
published: true
tags: ["Beginners", "Tutorial", "JavaScript", "Webdev"]
series: JavaScript Data Structures
---

## Intro 🌐

[Last time](https://dev.to/miku86/javascript-data-structures-hash-table-get-keys-550b), we learned how to get the keys from our hash table.

Today, we'll learn how to get the values of our Hash Table.

---

## Requirements 💭

We need the following parts to get the values from our Hash Table:

- a method to get the values (`values`)

---

## Starter Code ▶️

We start with [the code with the `set` method](https://dev.to/miku86/javascript-data-structures-hash-table-add-data-amc), so that we can use the `set` method to add some data.

```js
class Hashtable {
  constructor() {
    this.data = [];
    this.size = 0;
  }

  hash(key) {
    const chars = key.split("");
    const charCodes = chars.map((char) => char.charCodeAt());
    const charCodeSum = charCodes.reduce((acc, cur) => acc + cur);
    return charCodeSum;
  }

  set(key, value) {
    const hash = this.hash(key);

    if (!this.data[hash]) {
      this.data[hash] = [];
    }

    this.data[hash].push([key, value]);

    this.size++;
  }
}
```

If you are not familiar with the hash function, [re-read this post](https://dev.to/miku86/javascript-data-structures-hash-table-hash-function-2l71).

---

## Thoughts 💭

First, we should think about the constraints and possibilities:

- first, we declare an empty array for the values
- then we iterate over the data array
- if there is data (= array of key-value pairs) at this specific index, iterate over this data (= the single key-value pairs)
- add the data (= value) to the values array
- return the values array

As you can see, the steps are nearly the same as in our [last part](https://dev.to/miku86/javascript-data-structures-hash-table-get-keys-550b), where we got our keys.

---

## Example

We want to get all the values.

```js
// current hash table data:
[
  [["age", 33]],
  [
    ["name", "miku86"],
    ["mean", false],
  ],
];

// desired data:
[33, "miku86", false];
```

---

## Steps

```js
// current hash table data:
[
  [["age", 33]],
  [
    ["name", "miku86"],
    ["mean", false],
  ],
];

// then we iterate over the data array
[["age", 33]];

// if there is data (= array of key-value pairs) at this specific index
// then iterate over this data (= the single key-value pairs)
["age", 33];

// add the data (= value) to the values array
[33];

// then we iterate over the data array
[
  ["name", "miku86"],
  ["mean", false],
];

// if there is data (= array of key-value pairs) at this specific index
// then iterate over this data (= the single key-value pairs)
["name", "miku86"];

// add the data (= value) to the values array
[33, "miku86"];

// if there is data (= array of key-value pairs) at this specific index
// then iterate over this data (= the single key-value pairs)
["mean", false];

// add the data (= value) to the values array
[33, "miku86", false];

// desired data:
[33, "miku86", false];
```

✅

---

## Implementation ⛑

```js
// a Hash Table class
class Hashtable {
  constructor() {
    this.data = [];
    this.size = 0;
  }

  hash(key) {
    const chars = key.split("");
    const charCodes = chars.map((char) => char.charCodeAt());
    const charCodeSum = charCodes.reduce((acc, cur) => acc + cur);
    return charCodeSum;
  }

  set(key, value) {
    const hash = this.hash(key);

    if (!this.data[hash]) {
      this.data[hash] = [];
    }

    this.data[hash].push([key, value]);

    this.size++;
  }

  values() {
    // declare an empty array for the values
    const values = [];

    // iterate over the data array (I call a single array a "bucket")
    for (let bucket of this.data) {
      // if there is data (= array of key-value pairs) at this specific index
      if (bucket) {
        // iterate over this data (= the single key-value pairs)
        for (let item of bucket) {
          // add the data (= value) to the values array
          values.push(item[1]);
        }
      }
    }

    // return the values array
    return values;
  }
}
```

**Note**: I'm using a `for ... of`-loop. If you don't know how this works, you can read about it on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of). You can use whatever you want to use, a default `for`-loop, a `for ... in`-loop, a functional approach etc.

---

## Result

```js
// create a new hash table
const newHashtable = new Hashtable();

// add three new key-value pairs
newHashtable.set("name", "miku86");
newHashtable.set("mean", false);
newHashtable.set("age", 33);

// show the hash table data
console.log(newHashtable.data);
// [ <301 empty items>, [ [ 'age', 33 ] ], <115 empty items>, [ [ 'name', 'miku86' ], [ 'mean', false ] ] ]

// show the values
console.log(newHashtable.values());
// [ 33, 'miku86', false ] ✅
```

✅

---

## Next Part ➡️

We managed to write a function to get all values, great work!

Next time, we'll learn how to get all key-value pairs (= entries) from our Hash Table.

Need some mentoring? [Click here](https://miku86.com/mentoring)!

---

## Further Reading 📖

- [Simple Wiki: Hash Table](https://simple.wikipedia.org/wiki/Hash_table)
- [Wikipedia: Hash Table](https://en.wikipedia.org/wiki/Hash_table)
- [Wikibooks: Hash Table](https://en.wikibooks.org/wiki/Data_Structures/Hash_Tables)

---

## Questions ❔

- How would you implement the `values`-function?
- How would you write this code in a functional style?
- Should we remove duplicate values?