Index
Array Adding and Removing Examples


An array is a collection of elements. We'll play with adding and removing (mutating) arrays.

Constructing and initializing an array

let coll;

//initialize empty array
coll = [];

//simple initialization
coll = [10, 20, 30, 40];
	
//initialization with vars
const a=100, b=200;
coll [a, b, 300, 400];
prn(coll);
Append element to array.

let coll;

//append elements to end of array
coll = [];
coll.push('Larry');
coll.push('Moe');
coll.push('Curley');
prn(coll);
Insert many elements into array

let coll;

coll = [];
coll.push('Curley', 'Moe', 'Larry');
prn(coll);
Add element to start of array.

let coll;

//append elements to end of array
coll = [10, 20, 30, 40];
coll.unshift(1001);
prn(coll);
Insert element(s) at given position

let coll;

//let's insert two elements between 10 and 20
//1=index to insert, 0=count to remove, then elements
coll = [10, 20, 30, 40];
coll.splice(1, 0, 1001, 1002);
prn(coll);
Remove element at given position. We'll borrow "splice" from used for insert, that has a remove option.

let coll;

coll = [0, 10, 20, 30, 40];
//remove element at index=1
//1=index to remove, 1=count to remove
prn('before: ' + coll);
coll.splice(1, 1);
prn('after: ' + coll);

coll = [0, 10, 20, 30, 40, 50, 60, 70];
//remove element at indexes 4, 5 and 6 (count = 3)
//4=index to remove, 2=count to remove
prn('before: ' + coll);
coll.splice(4, 3);
prn('after: ' + coll);
prn(coll);

Length and Access


We'll get the array length and also get array elements in this group.

This is how we get the length of an array

const coll = [10, 20, 30, 40];

const len = coll.length;
prn('coll: ' + coll);
prn('length: ' + len);

//or
prn('length is: ' + coll.length);
This is how access (get) elements in an array

const coll = [10, 20, 30, 40];

//index positions start at 0
prn('first element: ' + coll[0]);
prn('second element: ' + coll[1]);

//We can get the last element using length
const lastIndex = coll.length - 1;
prn('last element: ' + coll[lastIndex]);

More Example Sources


Here are a couple (among many more) online related example sources: