Blog

JavaScript Array, map, valueOf,indexOf and lastIndexOf

The map function of a JavaScript array applies a certain method to all elements and creates an array.
Example 1
The following method call will change all values to positive
function f() {
var a = Array(1,2,-3,4);
var b = a.map(Math.abs);
}
Output: a=1,2,-3,4
b=1,2,3,4
Example 2
The following method call will find the sqrt of all numbers.
function f() {
var a = Array(1,16,-16,4);
var b = a.map(Math.sqrt);
}
Output: a=1,16,-16,4
b=1,4,NaN,2

Example 3
The following example uses a user defined function.

function f() {
var a = Array(1, 16, -16, 4);
var s = a.map(myAbs);
}

function myAbs(x) {
x = Number(x);
if (x < 0)
x = -x;
return x;
}
Output: a=1,16,-16,4
b=1,16,16,4

Example 4
Use an anonymous function
function f() {
var a = Array(1, 16, -16, 4);
var s = a.map(
function(x) {
x = Number(x);
if (x < 0)
x = -x;
return x;
});
}
Output: a=1,16,-16,4
b=1,16,16,4


The valueOf function converts the array to a primitive type.
Example 1
function f() {
var a = Array(1,3,4);
var s = a.valueOf();
alert(a);
alert(s);
}
Output: a=1,3,4
b=1,3,4

The indexOf function returns the index on an element in the array.

Example 1

function f() {
var a = Array(1,3,4,5,7,9);
var s = a.indexOf(5);
}
Output: s=3

Example 2
function f() {
var a = Array(1,5,4,5,7,9);
var s = a.indexOf(5);
}
Output: s=1

Example 3
Searching for an element starting at a given position

function f() {
var a = Array(1,5,4,5,7,9);
var s = a.indexOf(5,2);
}

Output: s=3

Example 4
The indexOf function returns -1 if the value is not found.

 function f() {
var a = Array(1,5,4,5,7,9);
var s = a.indexOf(-5,2);
}
Output: s=-1

lastIndexOf function in JavaScript Arrays
The lastIndexOf function searches starting at the end of the array
Example 1
function f() {
var a = Array(1,5,4,5,7,9);
var s = a.lastIndexOf(5);
}
Output: s=-3

Example 2
The lastIndexOf function searches to the left starting at the second parameter.
function f() {
var a = Array(1,5,4,5,7,9);
var s = a.lastIndexOf(5,2);
}
Output: s=1