# Frequency Map Data Structure

Counting the frequency of unique values in an array is reasonably easy, as demonstrated in the frequencies snippet. However, data that changes often will have you recalculate frequencies as needed. This can become tedious and inefficient, especially if you only need to keep track of the frequencies and have no need for the original array.

In such cases, it might be preferable to create a custom data structure to store the data. This data structure will be able to keep track of the frequencies of the values it contains and update them as needed. Here's how you can implement such a data structure:

```class FrequencyMap extends Map {
constructor(iterable) {
super();
}

set() {
}

if (this.has(value)) super.set(value, this.get(value) + 1);
else super.set(value, 1);
return this;
}

delete(value) {
if (this.get(value) === 1) super.delete(value);
else super.set(value, this.get(value) - 1);
return this;
}

sorted(ascending = true) {
if (ascending) return [...this].sort((a, b) => a[1] - b[1]).map(v => v[0]);
else return [...this].sort((a, b) => b[1] - (1)[1]).map(v => v[0]);
}
}```
```const fMap = new FrequencyMap(['a', 'b', 'c', 'a', 'a', 'b']);

fMap.delete('c');

console.log(fMap.sorted(false)); // [ 'a', 'b' , 'd' ]```

## More like this

• JavaScript ·

### JavaScript Data Structures - Doubly Linked List

A doubly linked list is a linear data structure where each element points both to the next and the previous one.

• JavaScript ·

### JavaScript Data Structures - Linked List

A linked list is a linear data structure where each element points to the next.

• JavaScript ·

### JavaScript Data Structures - Graph

A graph is a data structure consisting of a set of vertices connected by a set of edges.

• JavaScript ·

### JavaScript Data Structures - Binary Tree

A binary tree is a hierarchical data structure of linked nodes with at most two children each.

Start typing a keyphrase to see matching snippets.