i

JavaScript

Compare function of Array

The sort function, sorts the values of an array. This works well for strings; for example, “Grapes” comes before “Orange”. But in case of numbers, this doesn’t work well – because if numbers are sorted, then “45” is greater than “210” because 4 is greater than 2. To solve this issue, the compare function is used.

Example:

var numbers = [34, 245, 7, 65, 89];

numbers.sort(

function(x, y){

return x–y

});

The sorted array will be 7, 34, 65, 89, 245.

The same compare function can be slightly modified as below to sort the array in descending order.

var numbers = [34, 245, 7, 65, 89];

numbers.sort(

function(x, y){

return y–x

});

The sorted array will be 245, 89, 65, 34, 7.

copyWithin():

copyWithin() is used to copy the array elements within the array.

Syntax:

array.copyWithin(target, start, end)

The function takes 3 arguments:

  • target – index to copy the elements to – required argument

  • start – index to start copying elements from – optional argument – default value is 0

  • end – index to stop copying elements from – optional argument – default value is length of the array

This will modify the original array.

Example:

var fruits = [“Apple”, “Banana”, “Orange”, “Grapes”];

fruits.copyWithin(1,0);

The modified fruits array will be Apple,Apple,Banana,Orange.

fill():

fill() is used to fill the specified array positions with a static value.

Syntax:

array.fill(value, start, end)

The function takes 3 arguments:

  • value – value to fill the array with – required argument

  • start – index to start filling the array – optional argument – default value is 0

  • end – index to stop filling the array – optional argument – default value is length of the array

This will modify the original array.

This is not supported in IE11 and earlier versions.

Example:

var fruits = [“Apple”, “Banana”, “Orange”, “Grapes”];

fruits.fill(“Litchi”, 1, 3);

The modified fruits array will be Apple,Litchi,Litchi,Grapes.

includes():

To find if an array contains a particular element, includes() is used. This method returns true if the element is present, false otherwise. includes() is case-sensitive.

Syntax:

array.includes(value, start)

The function takes 2 arguments:

  • value – value to search for– required argument

  • start – position to start searching the array – optional argument – default value is 0

Example:

var fruits = [“Apple”, “Banana”, “Orange”, “Grapes”];

fruits.includes(“Banana”);    // returns true

fruits.includes(“Banana”, 2);   // returns false

Array Iteration Methods:

JavaScript has array iteration methods that operate on each item of the array.

forEach():

The forEach() method calls a callback function for each element in the array.

Example:

var newValue = “”;

var numbers = [3, 6, 7, 9];

numbers.forEach(add);

functionadd(value, index, array) {

            newValue = newValue + (value + 10) + “
”;

            return newValue;

}

In the above example, 10 is added to each element of the array. The output of this function will be:

13

16

17

19

The function takes 3 arguments:

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above function, the other two arguments can be avoided, and the function can be rewritten as follows:

var newValue = “”;

var numbers = [3, 6, 7, 9];

numbers.forEach(add);

function add(value) {

            newValue = newValue + (value + 10) + “
”;

            return newValue;

}

map():

map() creates a new array by performing some computation on each element of the array. It does not modify the source array.

Example:

var numbers = [4, 6, 13, 27];

var newArray = numbers.map(multiply);

function multiply(value, index, array) {

            return value * 5;

}

In the above example, each element of the array is multiplied by 5. The output of this function will be20,30,65,135.

The function takes 3 arguments:

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above callback function, the other two arguments can be omitted.

filter():

filter() method operates on each element of the array and creates a new array based on the elements that satisfy the specified condition.

Example:

var numbers = [9, 15, 22, 18, 30];

var filteredArray = numbers.filter(evenNumber);

function evenNumber(value, index, array) {

            return value % 2 === 0

}

In the above example, each element of the array is checked if it is divisible by 2. The output of this function will be 22, 18, 30.

The function takes 3 arguments:

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above callback function, the other two arguments can be omitted.

reduce():

reduce() method operates on each element of the array and reduces it to a single value. It works on the elements from left-to-right. It does not modify the source array.

Example:

var numbers = [3, 12, 18, 27];

var product = numbers.reduce(multiply);

function multiply(total, value, index, array) {

            return total * value;

}

In the above example, the array is reduced to the product of the numbers in the array. The output of this function will be 17496.

The function takes 4 arguments:

  • total – initial/previous returned value

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above callback function, the other two arguments can be omitted.

An initial value can be passed to the reduce method.

var numbers = [3, 12, 18, 27];

var product = numbers.reduce(multiply, 10);

function multiply (total, value) {

            return total * value;

}

In case of the above example, the initial value of total is 10. So for the first iteration, 10 * 3 will be computed. The output of the above function will be 174960.

reduceRight():

reduceRight() method operates on each element of the array and reduces it to a single value.It does not modify the source array. It is similar to reduce(), the only difference beingreduceRight() works on the elements from right-to-left.

every():

every() is used to check if all the elements in the array satisfy the specified condition.

Example:

var numbers = [9, 15, 22, 18, 30];

var isDivisibleByTwo = numbers.every(isEven);

function isEven(value, index, array) {

            return value % 2 === 0

}

The above example is used to check if all the array elements are divisible by 2. The output of this function is false.

The function takes 3 arguments:

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above callback function, the other two arguments can be omitted.

some():

some() is used to check if at least one array element satisfies the specified condition.

Example:

var numbers = [9, 15, 22, 18, 30];

var isDivisibleByTwo = numbers.some(isEven);

function isEven(value, index, array) {

            return value % 2 === 0

}

The above example is used to check if at least one array element is divisible by 2. The output of this function will be true.

The function takes 3 arguments:

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above callback function, the other two arguments can be omitted.

indexOf():

indexOf() is used to find the index of the first occurrence of the element in the array.

Syntax:

array.indexOf(item, start)

The function takes 2 arguments:

  • item – element to be searched for in the array

  • start – the position from which the element mush be searched. If the start is negative, the search will start at the position given from the enduntil the end of the array.

If the item searched is not present in the array, indexOf() will return -1.

Example:

var fruits = [“Apple”, “Banana”, “Orange”, “Grapes”, “Orange”];

var index = fruits.indexOf(“Orange”);

The value of index will be 2.

lastIndexOf():

To find the last occurence of an element in an array, lastIndexOf() is used.

Syntax:

array.lastIndexOf(item, start)

The function takes 2 arguments:

  • item – element to be searched for in the array

  • start – the position from which the element mush be searched. If the start is negative, the search will start at the position given from the end until the beginning of the array.

If the item searched is not present in the array, indexOf() will return -1.

Example:

var fruits = [“Apple”, “Banana”, “Orange”, “Grapes”, “Orange”];

var index = fruits.lastIndexOf(“Orange”);

The value of index will be 4.

All the above array iteration methods are supported in all browsers except IE 8 or earlier.

find():

find() is used to find the value of the first element in the array that satisfies the specified condition.

Example:

var numbers = [9, 15, 22, 18, 30];

var isDivisibleByTwo = numbers.find(isEven);

function isEven(value, index, array) {

            return value % 2 === 0

}

The above example finds the first element in the array that is divisible by 2. The output of this function will be 22.

The function takes 3 arguments:

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above callback function, the other two arguments can be omitted.

findIndex():

findIndex() is used to find the position of the first element in the array that satisfies the specified condition.

Example:

var numbers = [9, 15, 22, 18, 30];

var isDivisibleByTwo = numbers.findIndex(isEven);

function isEven(value, index, array) {

            return value % 2 === 0

}

The above example is used to find the index of first element in the array that is divisible by 2. The output of this function will be 2.

The function takes 3 arguments:

  • value – each element of the array

  • index – the position of the element in the array

  • array itself

Since only value is used in the above callback function, the other two arguments can be omitted.