[JavaScript] Arrays

In JavaScript, an array is a main weapon to manipulate a collection of data. In other programming languages, the strongly typed generic collections are preferred to arrays. But in the JavaScript world in which you do not specify types, arrays will do the work. In fact, JavaScript array is very powerful and has many features.

1. Features of JavaScript Arrays

JavaScript array is an object so it has properties and methods.

  • untyped : an element may be of any type
  • zero-based
  • dynamic : can be grown and shrunk as needed
  • type of object : array is an object

ECMAScript 5 enhanced the iteration feature of an array and provides very useful methods.

 

2. Creating an Array using Literals

Using the array literals is the frequently used way to create arrays. Array literals are comma separated values within square brackets.

var oddNums = [1, 3, 5, 7, 9];
var hello = ['H', 'e', 'l', 'l', 'o'];
alert(oddNums.length);
alert(hello.join(""));

 

3. Creating an Array using Constructors

An array is an object so you can create an array using the “new” keyword.

  • Array() : creates an empty array
  • Array(length) : creates an array of the specified length
  • Array(value1, value2, …) : create an array with the values – in general, array literals are used instead of this constructor
var oddNums = new Array();
oddNums[0] = 1;
oddNums[1] = 3;
oddNums[2] = 5;

var hello = new Array('H', 'e', 'l', 'l', 'o');
alert(oddNums.length);
alert(hello.join(""));

 

4. Getting the Length

The “length” property is used to get the size of an array.

var nums = new Array(10);
alert(nums.length); // 10

 

5. Sorting

The “sort()” method sort the array in the alphabetic ascending order.

var nums = [1, 8, 2, 7, 4, 3, 6, 5, 9];
var numsSorted = nums.sort();
alert(nums.join());
alert(numsSorted.join());

Note that the “sort()” method changes the order of the target array itself unlike most of the string methods.

Now, what does it mean “alphabetical”?

If you sort 10 and 2, 10 comes before 2. All numbers are actually converted to characters and sorted. The default implementation of the “sort()” method is very limited. The good news is that you can provide the custom comparison function as an argument.

The comparison function takes 2 parameters and as follows

  • less than 0 : the first parameter appears BEFORE the second parameter
  • greater than 0 : the first parameter appears AFTER the second parameter
  • 0 : the two parameters are equal

Let’s sort numeric values.

function sortNumericAscending(a, b) {
  return a - b;
}
function sortNumericDescending(a, b) {
  return b - a;
}

$(document).ready(function () {
  var nums = [1,10,2,20,3,30];
  alert(nums.sort().join()); // 1,10,2,20,3,30
  alert(nums.sort(sortNumericAscending).join()); // 1,2,3,10,20,30
  alert(nums.sort(sortNumericDescending).join()); // 30,20,10,3,2,1
});

 

6. Joining, Concatenating and Slicing

Joining and concatenating look similar but do the completely different tasks in Array.

  • join(separator) : joins all elements of an array into a string (the default separator is a comma)
  • concat(array1, array2, …, arrayX) : joins two or more arrays, and returns a copy of the joined arrays
var oddnums = [1, 3, 5, 7, 9];
var evennums = [2, 4, 6, 8, 10];
var nums
= oddnums.concat(evennums).sort(function (a, b) { return a - b; });
alert(nums.join()); // 1,2,3,4,5,6,7,8,9,10

The “slice()” method does the opposite of “concat()“. It slices a part of an array and returns it as a new array.

  • slice(startIndex, endIndex)

The endIndex can be omitted if you want to select till the end.

var nums = [1, 2, 3, 4, 5];
alert(nums.slice(1,3)); // 2,3
alert(nums.slice(2)); // 3,4,5
alert(nums.slice(1, -1)); // 2,3,4

Note that “concat()” and “slice()” do not modify the array on which they are invoked.

 

7. Reversing

The “reverse()” method reverses the order of the elements in an array. Do not confuse this with sorting.

var nums = [1, 10, 2, 20, 3, 30];
alert(nums.join()); // 1,10,2,20,3,30
nums.reverse();
alert(nums.join()); // 30,3,20,2,10,1

 

8. Splicing (?)

The “splice()” method adds or removes elements from an array. It modifies the target array directly. It returns the removed items.

  • splice(index) : removes elements from the index to the end
  • splice(index, howmany) : removes specified number of elements from the index
  • splice(index, howmany, item1, ….., itemX) : removes specified number of elements from the index and adds new elements
var nums = [1, 2, 3, 4, 5];
alert(nums.splice(2)); // 3,4,5
alert(nums); // 1,2

nums = [1, 2, 3, 4, 5];
alert(nums.splice(2,2)); // 3,4
alert(nums); // 1,2,5

nums = [1, 2, 3, 4, 5];
alert(nums.splice(2, 0, 7, 8)); //
alert(nums); // 1,2,7,8,3,4,5

nums = [1, 2, 3, 4, 5];
alert(nums.splice(2, 3, 7, 8)); // 3,4,5
alert(nums); // 1,2,7,8

 

9. Push and Pop

Arrays can be used as a stack.

  • push(item1, item2, …, itemX) : appends one or more elements to the end of an array
  • pop() : removes the last element and returns that element.
var nums = [1, 2, 3, 4, 5];
alert(nums.length); // 5
nums.push(6, 7, 8);
alert(nums.length); // 8
alert(nums.pop()); // 8
alert(nums.pop()); // 7
alert(nums.length); // 6

 

10. Shift and Unshift

The “shift()” and “unshift()” methods behave much like “push()” and “pop()“, except they add or remove elements from the beginning of an array. Note that “unshift()” adds elements and “shift()” removes the first one.

  • unshift(item1, item2, …, itemX)
  • shift()
var nums = [1, 2, 3, 4, 5];
alert(nums.length); // 5
nums.unshift(6, 7, 8);
alert(nums); // 6,7,8,1,2,3,4,5
alert(nums.shift()); // 6
alert(nums.shift()); // 7
alert(nums.length); // 6

 

11. toString

The “toString()” method converts an array into a String (comma separated list) and returns the result. It works like the “join()” method.

var nums = [1, 2, 3, 4, 5];
alert(nums.toString()); // 1,2,3,4,5

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s