Cynical news

Links
Literature
Music
Programming
Software
Programming
JavaScript Arrays
JavaScript Arrays
Initialise

Fixed contents n/a a=[1,2,3,4,5];
1 2 3 4 5

Insert

Prepend element 'e' a=[2,3,4]
e=1;
a.unshift(e);
1 2 3 4
Append element 'e' a=[1,2,3]
e=4;
a.push(e);
1 2 3 4
Insert element 'e' at index 'n' a=[1,2,3,4,5]
e=666
n=3
a.splice(n,0,e);
1 2 3 666 4 5
Prepend array 'b' a=[1,2,3,4,5]
b=[10,20,30]
a=b.concat(a);
10 20 30 1 2 3 4 5
Append array 'b' a=[1,2,3,4,5]
b=[10,20,30]
a=a.concat(b);
1 2 3 4 5 10 20 30
Insert array 'b' at index 'n' a=[1,2,3,4,5]
b=[10,20,30]
n=3;
for (i=0; i<b.length; i++) { a.splice(n+i,0,b[i]) }
1 2 3 10 20 30 4 5
Concatenate array 'a' and array 'b' a=[1,2,3]
b=[4,5,6]
c=a.concat(b);
1 2 3 4 5 6
Insert element 'e' at indices in 'b' a=[1,2,3,4,5]
b=[0,2,4]
e=666
for (i=0; i<b.length; i++) { a.splice(b[i]+i,0,e) }
666 1 2 666 3 4 666 5
Insert element 'e' 'n' times at index 'm' a=[1,2,3]
n=3
m=1
e=666
for (i=0; i<n; i++) { a.splice(m,0,e) }
1 666 666 666 2 3

Overwrite

Overwrite first element a=[1,2,3]
a[0]=666;
666 2 3
Overwrite last element a=[1,2,3]
a[a.length-1]=666;
1 2 666
Overwrite element at index 'n' a=[1,2,3]
n=1
a[n]=666;
1 666 3
Overwrite elements from index 'n' (inclusive) a=[1,2,3,4,5,6]
b=[7,8,9]
n=2
for (i=0; i<b.length; i++) { a.splice(n+i,1,b[i]) }
1 2 7 8 9 6

Count

Length of array a=[1,2,3]
n=a.length;
3

Retrieve by index

Retrieve first element a=[1,2,3]
e=a[0];
1
Retrieve last element a=[1,2,3]
e=a[a.length-1];
3
Retrieve element 'n' a=[1,2,3]
n=2
e=a[n];
3

Remove by index

Remove element at index 'n' a=[1,2,3,4,5]
n=2;
a.splice(n,1);
1 2 4 5
Remove elements in index range 'm' to 'n' (inclusive) a=[1,2,3,4,5]
m=1;
n=3;
a.splice(m,n-m+1);
1 5
Remove elements from index 'n' onwards (inclusive) a=[1,2,3,4,5]
n=3;
a .splice(n,a.length-n+1);
1 2 3

Slice

Slice from index 'm' to 'n' (inclusive) a=[1,2,3,4,5]
m=1
n=3
a=a.slice(m,n+1);
2 3 4
Slice from index 'n' onwards (inclusive) a=[1,2,3,4,5]
n=2
a=a.slice(n);
3 4 5
Slice up to index 'n' (inclusive) a=[1,2,3,4,5]
n=3;
a=a.slice(0,n+1);
1 2 3 4
Slice up to 'n' elements from end a=[1,2,3,4,5]
n=2
a=a.slice(0,-n);
1 2 3

Sort

Sort in ascending order a=[5,1,4,3,2]
a.sort();
1 2 3 4 5
Sort in descending order a=[5,1,4,3,2]
a.sort(reverse_sort);
5 4 3 2 1
Reverse a=[1,2,3,4,5]
a.reverse();
5 4 3 2 1

Use as a stack

Push element 'e' a=[1,2,3,4,5]
e=666;
a.push(e);
1 2 3 4 5 666
Pop next element a=[1,2,3,4,5]
a.pop();
1 2 3 4
Retrieve next element a=[1,2,3,4,5]
e=a[a.length-1];
5

www.cynicalsoftware.com
14-11-09@15:37:24