06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Data Structures and Manipulation<br />

The sort() method sorts the elements of an array:<br />

var myArray = new Array("A", "C", "B");<br />

myArray.sort();<br />

// sorts the array so that myArray = [ "A","B","c" ]<br />

The sort() method can optionally take a callback function to define how the<br />

elements are compared. The function compares two values and returns one of three<br />

values. Let us study the following functions:<br />

• indexOf(searchElement[, fromIndex]): This searches the array for<br />

searchElement and returns the index of the first match:<br />

var a = ['a', 'b', 'a', 'b', 'a','c','a'];<br />

console.log(a.indexOf('b')); // 1<br />

// Now try again, starting from after the last match<br />

console.log(a.indexOf('b', 2)); // 3<br />

console.log(a.indexOf('1')); // -1, 'q' is not found<br />

• lastIndexOf(searchElement[, fromIndex]): This works like indexOf(),<br />

but only searches backwards:<br />

var a = ['a', 'b', 'c', 'd', 'a', 'b'];<br />

console.log(a.lastIndexOf('b')); // 5<br />

// Now try again, starting from before the last match<br />

console.log(a.lastIndexOf('b', 4)); // 1<br />

console.log(a.lastIndexOf('z')); // -1<br />

Now that we have covered <strong>JavaScript</strong> arrays in depth, let me introduce you to a<br />

fantastic library called Underscore.js (http://underscorejs.org/). Underscore.js<br />

provides a bunch of exceptionally useful functional programming helpers to make<br />

your code even more clear and functional.<br />

We will assume that you are familiar with Node.js; in this case, install Underscore.js<br />

via npm:<br />

npm install underscore<br />

As we are installing Underscore as a Node module, we will test all the examples by<br />

typing them in a .js file and running the file on Node.js. You can install Underscore<br />

using Bower also.<br />

Like jQuery's $ module, Underscore comes with a _ module defined. You will call all<br />

functions using this module reference.<br />

[ 90 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!