Native JavaScript Data Structures – 30 seconds of code


Arrays

An array is a linear data structure that represents a collection of elements. In JavaScript, arrays don’t have a fixed size, while their contents can be of any valid type, even arrays themselves. Arrays are probably the most commonly used data structure and come with a plethora of methods that allow easy manipulation and transformation of their contents.

const nums = [1, 2, 3];
const strs = Array.from('est');

nums.push(6);
nums.push(4, 9);
strs.unshift('t');

nums.length;                     
nums[nums.length - 1];           
strs[0];                         
strs[2];                         

nums.slice(1, 3);                
nums.map(n => n * 2);            
nums.filter(n => n % 2 === 0);   
nums.reduce((a, n) => a + n, 0); 

strs.reverse();                  
strs.join('');                   

Sets

A set is a linear data structure that represents an ordered collection of unique values. Sets in JavaScript can store any valid type of value, however each value can only occur once based on value equality checking.

const nums = new Set([1, 2, 3]);

nums.add(4);
nums.add(1);
nums.add(5);
nums.add(4);

nums.size;                       
nums.has(4);                     

nums.delete(4);
nums.has(4);                     

[...nums];                       

nums.clear();
nums.size;                       

Maps

A map is an associative data structure that represents a keyed collection of elements. Each key in a JavaScript Map has to be unique and either a primitive value or an object, whereas the values of the map can be of any valid type.

const items = new Map([
  [1, { name: 'John' }],
  [2, { name: 'Mary' }]
]);

items.set(4, { name: 'Alan' });
items.set(2, { name: 'Jeff' });

items.size;                      
items.has(4);                    
items.get(2);                    

items.delete(2);
items.size;                      

[...items.keys()];               
[...items.values()];             

items.clear();
items.size;                      



Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here