javascript collections

Javascript Keyed and Indexed Collections Array, Map and Set

In this article we will learn about dealing with collections in Javascript and will take a look at some advanced collections which are Maps and Sets.

 

In javascript there are a lot of methods to deal with collections. Like in languages such as PHP or Java there are collections that has numeric indices and these called indexed collections, collection that has associative indices and these called keyed collections that have a key of any type. In this tutorial we will take a look at each of these methods so let’s begin with arrays.

 

Indexed Collections (Arrays)

arrays is the indexed collection in javascript. Array is an ordered set of values that has a numeric index and value. For example, you could have an array called employees that contains employees’ names indexed by their numerical employee number.

Creating an array

as shown above there are a lot of ways of creating arrays. When you initialize arrays in this way the length property is set to the number of arguments supplied.

Another way is to initialize the array with the number of items then add values like this:

If you need to create a variable length array and populate as you go use this approach:

 

Referring to array elements

To access array elements you use the index of the element as shown here:

As shown above Arrays is zero based indices which means index of the elements begins with zero so to access the first element you do this with Array[0].

 

Obtaining array length

To get the number of elements in array use Array.length like this:

There are some caution when dealing with length property so consider this example:

In the above code someone might guess that cats array has one element so it should have a length of 1. But here the first element has index of 30 so if you print  the array it will show 31 elements starting with zero and this is because the length property always returns the index of the last element plus one (as above 30 + 1) = 31.

 

Iterating over arrays

There are multiple ways to iterate over arrays. First way using standard for loop:

The forEach() method provides another way of iterating over an array:

Alternatively, You can shorten the code for the forEach parameter with ES2015 Arrow Functions:

 

Array methods

concat() joins two arrays and returns a new array.

 

join(delimiter = ',') joins all elements of an array into a string.

 

push() adds one or more elements to the end of an array and returns the resulting length of the array.

 

pop() removes the last element from an array and returns that element.

 

shift() removes the first element from an array and returns that element.

 

unshift() adds one or more elements to the front of an array and returns the new length of the array.

 

slice(start_index, upto_index) extracts a section of an array and returns a new array.

 

splice(index, count_to_remove, addElement1, addElement2, ...)

removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.

 

reverse() transposes the elements of an array, in place: the first array element becomes the last and the last becomes the first. It returns a reference to the array.

 

sort() sorts the elements of an array in place, and returns a reference to the array.

 

indexOf(searchElement[, fromIndex]) searches the array for searchElement and returns the index of the first match.

 

map(callback[, thisObject]) returns a new array of the return value from executing callback on every array item.

 

filter(callback[, thisObject]) returns a new array containing the items for which callback returned true.

 

Keyed Collections

keyed collections or in some terms called associative. Collections of data which are ordered by a key, Map and Set objects contain elements which are iterable in the order of insertion.

 

Maps

ECMAScript 2015 introduces a new data structure to map values to values. A Map object is a simple key/value map and can iterate its elements in order of insertion.

Syntax

Map take optional parameter iterable which is an Array or other iterable object whose elements are key-value pairs.

 

Adding elements

As shown in the code above to add elements to the map use Map.set(key, value).

 

Map properties and methods

Retrieve the size of map with Map.size property:

Get specific item by key with Map.get(key):

Check if an item exists with Map.has(key):

To delete an item from map use Map.delete(key):

Clear all the map elements with Map.clear():

 

Iterating over map items:

Maps can be iterated using a for..of loop as shown here:

Maps also can be iterated using the forEach() method:

 

Let’s look at some examples:

As shown in the code above the Map keys can be anything (primitive values, objects or functions).

Using NaN as Map keys

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other.

 

Demonstrating keys(), values(), and entries():

 

 

Object and Map Differences:

Traditionally, objects have been used to map strings to values. Objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Map objects, however, have a few more advantages that make them better maps.

  • The keys of an Object are Strings, where they can be of any value for a Map.
  • You can get the size of a Map easily while you have to manually keep track of size for an Object.
  • The iteration of maps is in insertion order of the elements.
  • An Object has a prototype, so there are default keys in the map. (this can be bypassed using map = Object.create(null)).

 

Converting Maps To Arrays and vice versa:

 

Sets

The Set object lets you store unique values of any type, whether primitive values or object references. Set differs from Maps in that it does not contain explicit keys because it’s a collection of values and keys is the same as values.

Like Maps you can iterate Set elements in the order of insertion. But note that a value in a Set may only occur once; it is unique in the Set‘s collection.

Syntax

If an iterable object is passed, all of its elements will be added to the new Set. If you don’t specify this parameter, or its value is null, the new Set is empty.

 

Adding Elements

As shown above you can add any arbitrary values in the Set. You can add primitive values, objects, arrays, also undefined and Nan.

 

Set properties and methods

Retrieve the size of set with Set.size property:

Check if a value exists with Set.has(value):

To remove an element from set use Set.delete(value):

To clear all Set values use Set.clear():

 

Iterating over set items:

using for .. of loop as shown in this code:

You can also iterate Sets using Set.forEach(callback):

 



Let’s look at few examples:

 

Set keys(), values(), and entries():

values() returns a new Iterator object that contains the values for each element in the Set object in insertion order.

keys() is the same function as the values() function and returns a new Iterator object that contains the values for each element in the Set object in insertion order.

entries() returns a new Iterator object that contains an array of [value, value] for each element in the Set object, in insertion order

 

Array and Set Differences:

Traditionally, a set of elements has been stored in arrays in JavaScript in a lot of situations. The new Set object, however, has some advantages:

  • Checking whether an element exists in a collection using indexOf for arrays is slow.
  • Set objects let you delete elements by their value. With an array you would have to splice based on an element’s index.
  • The value NaN cannot be found with indexOf in an array.
  • Set objects store unique values; you don’t have to keep track of duplicates by yourself.

 

Converting Sets To Arrays and vice versa:

 

Share this: