JavaScript Collection

In any programing language, we use specific way to hold the same data under one variable, It could be array, list, dictionary, has or map many more, in general we call it a collection. Each programing language has its own way to handle data set. In JavaScript, Array, Map, Set and most popular types. So each method has its own pros and cons.

Array

In javascript array is defined as below.

var array = [];
or
var array = new Array();

It supports any data type, could be string, integer, decimal, object or even function.

var array = [
1,
10.0,
{},
"Test",
function Test() {}
]
or
var multidimensionalArray = [
[1, 2],
[ "name" , "age"]
]

JS array is an Object which has length property to get how many key exist on that. Remember, when increase or decrease length property, will affect to elements in array.

typeof array // object

var array = ['banana', 'apple', 'peach'];
array.length = 4;
console.log(array) // [‘banana’, ‘apple’, ‘peach’, empty]

array.length = 2;
console.log(array) // [‘banana’, ‘apple’ ]

Access item in Array

By using index, we can easily access item in array by using index.

array[index]

push(), pop(), shift() and unshift()

These methods are really important when working with array. each method has own unique operation to deal with array.

Iterate over Array items

Below mechanism use to iterate over collection and for loop is the most widely used way and more efficient for large collection.

let array = ["Apple", "Orange", "Peach"];

for (let i = 0; i < array.length; i++) {
  alert( array[i] );
}

for(var key in array){
  console.log(array[index])
}

for(var item of array){
   console.log(item)
}

array.forEach(function(item){
   console.log(item);
});

Map vs Set

These data structure were introduced in ES6.

Map – is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any data type.

let map = new Map();

map.set('1', 'string');   // a string key
map.set(1, 'number');     // a numeric key
map.set(true, 'boolean'); // a boolean key

console.log( map.get(1)   ); // number
console.log( map.get('1') ); // string

console.log( map.size ); // 3

let manoj= { name: "Manoj" };
map.set(manoj, 'user 1');

console.log( map.get(manoj) ) // user 1

Common method for map

  • new Map() – creates the map.
  • map.set(key, value) – stores the value by the key.
  • map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
  • map.has(key) – returns true if the key exists, false otherwise.
  • map.delete(key) – removes the value by the key.
  • map.clear() – removes everything from the map.
  • map.size – returns the current element count.

Set – is a special type collection where each value may occur only once.
Basic idea is to remove duplicate value from a collection, you can easily use this.

let set = new Set();

set.add('item one');
  • new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
  • set.add(value) – adds a value, returns the set itself.
  • set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
  • set.has(value) – returns true if the value exists in the set, otherwise false.
  • set.clear() – removes everything from the set.
  • set.size – is the elements count.
//Remove duplicate value from array
var a = [1,2,2,3];
var set = new Set(a);
console.log(set); // Set(3) {1, 2, 3}

WeakMap and WeakSet

Most important thing is, these two data structure support for garbage collector to clear the memory when main object is inaccessible.

First look at below code, when main object set to null, still array[0] holding that memory space allocate for the object.

var obj = { name : 'manoj' }
var array = [obj];
obj = null; 
//In this case array object still exist and garbage collector will not //clear the memory space allocate for obj in array.

WeakMap – Only different from Map is, key must be an object.

let weakMap = new WeakMap();

let obj = {};

weakMap.set(obj, "weakMap");

obj = null; //garbage collector will clean up th object in weakmap too

WeakSet – Only different from Set is, it does not support primitive type as key, must be an object.

let weakSet = new WeakSet();

let obj = {};

weakSet.set(obj);

obj = null; //garbage collector will clean up th object in weakmap too

One Reply to “JavaScript Collection”

Leave a Reply