# Javascript Array Sort Search

## Reordering Methods

There are two methods we can use to reorder an array: reverse() and sort().

Both reverse() and sort() return a reference to the array on which they were applied.

## reverse()

reverse() method reverses the order of items in an array.

``````
var values = [1, 2, 3, 4, 5];
values.reverse();
console.log(values);       //5,4,3,2,1

``````

The code above generates the following result.

## sort()

By default, the sort() method sort items in ascending order.

sort() calls String() on every item and then compares the strings to determine the order, even if all items in an array are numbers.

``````
var values = [0, 1, 5, 10, 15];
values.sort();
console.log(values);    //0,1,10,15,5

``````

Even though 5 is less than 10, the string "10" comes before "5".

The code above generates the following result.

## Comparison function

sort() method can have in a comparison function to indicate the sequence.

A comparison function accepts two arguments and returns

• a negative number if the first argument should come before the second,
• a zero if the arguments are equal
• a positive number if the first argument should come after the second.

Here's an example of a simple comparison function:

``````
function compare(value1, value2) {//w ww .  j av  a  2s.c  o  m
if (value1 < value2) {
return -1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values);    //0,1,5,10,15

``````

To sort in descending order, switch the return values like this:

```function compare(value1, value2) {
if (value1 < value2) {
return 1;
} else if (value1 > value2) {
return -1;
} else {
return 0;
}
}

var values = [0, 1, 5, 10, 15];
values.sort(compare);
console.log(values);    //15,10,5,1,0
```

## Search Methods

Javascript array has two methods for search: indexOf() and lastIndexOf().

They both accept two arguments: the item to look for and an optional index from which to start looking.

indexOf() searches from array start while lastIndexOf() searches from the last item and continues to the front.

They will return the position of the item or -1 if the item isn't in the array.

An identity comparison (===) is used during comparing.

## Search Methods Example

``````
var numbers = [1,2,3,4,5,6,5,4,3,2,1];
/* ww  w  .ja  v a 2 s  . co m*/
console.log(numbers.indexOf(4));
console.log(numbers.lastIndexOf(4));

console.log(numbers.indexOf(4, 4));
console.log(numbers.lastIndexOf(4, 4));

var person = { name: "A" };
var people = [{ name: "A" }];

var morePeople = [person];

console.log(people.indexOf(person));
console.log(morePeople.indexOf(person));
``````

The code above generates the following result.