If you are hearing about arrays as a data type for the first time, you should take a step back and read up on the Introduction to DataTypes to get a grasp first.

Array.slice()

This method allows you to take a “slice” of data from your original array and save this slice to a new array.
The syntax of the method is like:

array.slice()
array.slice(begin)
array.slice(begin, end)

The begin parameter is an optional zero-based index, indicating at which point to start the extraction. If a negative index is used, then an offset from the end of the array will be used.

The end parameter is again an optional zero-based index, indicating at which point to end the extraction, excluding end. Again if a negative index is used, then an offset from the end of the array will be used.

var fruits = ["Banana","Orange","Lemon","Apple","Mango"];
var citrus = fruits.slice(1,3);

console.log(fruits); // logs ["Banana", "Orange", "Lemon", "Apple", "Mango"]
console.log(citrus); // logs ["Orange", "Lemon"]

Note that the original fruits array remains unchanged.

Array.splice()

array.splice() is another method to create a new array from elements of an existing array. Even though the function is similar to array.slice(), its behaviour is a bit different.
The syntax of the method looks like:

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

The start is an index at which to start changing the array (starting at 0). If you provide a negative value, the splice will start that many positions from the end of the array, counting backwards.

The deleteCount is an optional parameter, indicating how many items to remove from the original array. If you set this value to 0, no item will be removed. If you provide a number that is greater than or equal to the size of the array, then all elements of the array will be removed.

The item1, item2, … are optionally the items you want to add to the array. If you don’t specify any item, then splice() will only remove items from the list.

Insert element in position
var loyalists = ["Ferrus Manus", "Sanguinius", "Jaghatai Khan", "Rogal Dorn"];

var removed = loyalists.splice(2, 0, "Alpharius");
//loyalists are now ["Ferrus Manus", "Sanguinius", "Jaghatai Khan", "Rogal Dorn","Alpharius"]
//removed is [], no elements removed
Remove one element
var fish = ["angel","clown", "drum", "mandarin", "sturgeon"];
var removed = fish.splice(3,1);

//fish is ["angel", "clown", "drum", "sturgeon"]
//removed is ["drum"]
Remove one element and add another
var fish = ["angel", "clown", "drum", "sturgeon"];
var removed = fish.splice(3, 1, "trumpet");

//fish is ["angel", "clown", "drum", "trumpet"]
//removed is ["sturgeon"]

Array.push() & Array.pop()

So now that we have seen how to add and remove elements in a specific location of our list, it is time to see how to add and remove items in general.
To add a new element in the list we can use the Array.push() method.
The syntax of the method is like:

array.push([element1[, ...[, elementN]]])

The elementN is a list of the elements that we want to add to the end of the array.
The function returns the new length of the array.

var numbers = [1,2,3];
numbers.push(4);
console.log(numbers); //logs [1, 2, 3, 4]

In the last example, we saw that arrays can contain integers. However, you can push any data type to an array. Check the following messy example.

var stuff = ["purple",123.312,"chicken",["nested","array"]]; 
stuff.push(42);
stuff.push({name:"Rowboat Girlyman",profession:"SPESS MEHREEN"});
console.log(stuff); // logs ["purple",123.312,"chicken",["nested","array"],42,{name:"Rowboat Girlyman",profession:"SPESS MEHREEN"}]

We can also push multiple values in the array.

ar users = ["Anna","Ben","Jim","John"];  
users.push("Peter","Bob","Jenny");  
console.log(users); // ["Anna","Ben","Jim","John","Peter","Bob","Jenny"]

array.pop(), is array.push()‘s evil twin. It simply removes an element from the end of the list.

var a = [1, 2, 3];
a.pop();

console.log(a) // logs [1, 2]

If we want to store the poped value, we can assign it to a variable.

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var popped = myFish.pop();
console.log(myFish); // logs ['angel', 'clown', 'mandarin' ] 
console.log(popped); // logs 'sturgeon'

Array.shift() & Array.unshift()

Ok, now we know how to add an element at the end of the array. What if we wanted to do the same thing to the beginning of our array? This is exactly what Array.shift() and Array.unshift() functions do.

Array.shift() removes an element from the beginning of the array. If we want to keep the removed value we can assign it to a variable.

var a = [1, 2, 3];
var b = a.shift();

console.log(a); // logs [2, 3]
console.log(b); // logs 1

Array.unshift() adds an element at the beginning of the array.

var arr = [1, 2];

arr.unshift(0); // result of call is 3, the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]

Array.join()

Sometimes, we want to display the contents of an array as a string. The Array.join() function comes to the rescue!
The syntax of the function is like:

arr.join()
arr.join(separator)

The separator argument is an optional string used to separate each element of the array. If needed the separator will be converted to string. If no argument is used, a comma (“,”) will be used. Finally, if an empty string is provided, all elements are joined without any characters in between them.

var a = ['Wind', 'Rain', 'Fire'];
a.join();      // 'Wind,Rain,Fire'
a.join(', ');  // 'Wind, Rain, Fire'
a.join(' + '); // 'Wind + Rain + Fire'
a.join('');    // 'WindRainFire'

Array.reverse()

This method is pretty much self-explanatory. It’ll reverse the order of all elements within the array.

var a = ['one', 'two', 'three'];
var reversed = a.reverse(); 

console.log(a);        // logs ['three', 'two', 'one']
console.log(reversed); // logs ['three', 'two', 'one']

Array.sort()

The last array method we are looking at in this post is Array.sort(). This method will sort strings in your array alphabetically.

var fruit = ['cherries', 'apples', 'bananas'];
console.log(fruit.sort()); // logs ['apples', 'bananas', 'cherries']

If we wanted to sort the array from Z-A instead of A-Z, we could simply combine this method with Array.reverse()

var fruit = ['cherries', 'apples', 'bananas'];
console.log(fruit.sort().reverse()); // logs ["cherries", "bananas", "apples"]

If you want to use array.sort() with numbers however, you will run into trouble. Let’s try sorting a simple array with numerical values.

myArr = [1,5,200,30,29,24,12];  
myArr.sort();  
console.log(myArr); // logs [ 1, 12, 200, 24, 29, 30, 5]

To understand this behaviour of our sort method, we have to go back to the basics about data types and operators. The sort function will consider your numbers as strings as therefore only look at the first character of each number and order them accordingly. So in the eyes of our function, the array now looks like [1,1,2,2,2,3,5]. If we really want to compare the value of numbers in our sort function, we need a compare function. This is not yet the time to discuss how to write your own logic in a compare function. For now, you should know that there are two compare functions that will allow you to sort numbers in an ascending or descending order:

myArr = [1,5,200,30,29,24,12]  
myArr.sort(function(a,b){return a-b});  
console.log(myArr);  
// ascending order
// logs [ 1, 5, 12, 24, 29, 30, 200 ];
myArr.sort(function(a,b){return a+b});  
console.log(myArr);  
// descending order
// logs [ 200, 30, 29, 24, 12, 5, 1 ];
Advertisements