BlogsDope image BlogsDope

Function available for use on JavaScript Array

June 13, 2020 ARRAY JAVASCRIPT FUNCTION 1408

JavaScript arrays can be used to store multiple elements. The elements can be of different datatype and the length of the array is not fixed as well. There are many built-in functions that you can apply on arrays to perform operations like converting an array to a string, adding or removing elements from the array, etc. Let us discuss them in detail with examples.

push()


It adds one or more elements to the end of the array. Note that it modifies the underlying array and it returns the new length.  The syntax is array.push(el1, el2,el3, …., elN). Consider the following example.

sports = ["cricket", "football", "badminton", "basketball"]
length = sports.push("volleyball")
console.log(sports)
console.log("length: " + length)

Output

[‘cricket’, ‘football’, ‘badminton’, ‘basketball’, ‘volleyball’]
length: 5

Adding more than one element.

sports = ["cricket", "football", "badminton", "basketball"]
length = sports.push("volleyball","rugby")
console.log(sports)
console.log("length: " + length)

Output

[‘cricket’, ‘football’, ‘badminton’, ‘basketball’, ‘volleyball’, ‘rugby’]
length: 6

Note that leaving the argument empty does not generate an error. Instead, it adds nothing, and the array remains the same.

pop()


It removes an element from the end of the array and returns that element. The syntax is array.pop(). Let’s see an example.

sports = ["cricket", "football", "badminton", "basketball"]
deleted_element = sports.pop()
console.log(sports)
console.log("Deleted Element: " + deleted_element)

Output

[‘cricket’, ‘football’, ‘badminton’]
Deleted Element: basketball

pop() when applied on an empty array returns undefined.

sports = []
deleted_element = sports.pop()
console.log(sports)
console.log("Deleted Element: " + deleted_element)

Output

[]
Deleted Element: undefined

unshift()


It is similar to the push() method except it adds element(s) at the start of an array.

sports = ["cricket", "football", "badminton", "basketball"]
length = sports.unshift("volleyball","rugby")
console.log(sports)
console.log("length: " + length)

Output

[‘volleyball’, ‘rugby’,‘cricket’, ‘football’, ‘badminton’, ‘basketball’]
length: 6

shift()


It is similar to the pop() method except it removes an element from the start.

sports = ["cricket", "football", "badminton", "basketball"]
deleted_element = sports.shift()
console.log(sports)
console.log("Deleted Element: " + deleted_element)

Output

[ ‘football’, ‘badminton’,‘basketball’]
Deleted Element: cricket

splice()


The splice() method can be either used to add or delete element(s) at any position. The syntax is array.splice(start, deleteCount, el1, el2 , …., elN), here the start parameter represents the position from where the new items are to be added/removed, deleteCount represents the number of elements to be deleted,  el1, el2, … elN, represents the elements to be inserted. The 2nd and 3rd parameters are optional. It returns an array of deleted elements. Let us consider some examples to understand this.

sports = ["cricket", "football", "badminton", "basketball"]
deleted_element = sports.splice(1, 2, "volleyball", "rugby")
console.log(sports)
console.log("deleted_element")
console.log(deleted_element)

Output

[ ‘cricket’, ‘volleyball’,‘rugby’,‘basketball’]
deleted_element
[ ‘football’, ‘badminton’]

Let’s break this down and understand what is happening.

The new elements will be inserted from index 1. The second parameter shows 2 elements will be deleted from the index 1 i.e. “football” and “badminton”. The elements that will be added from index 1 are “volleyball” and “rugby”.

Let’s see how the splice() method can be used to add elements only.

sports = ["cricket", "football", "badminton", "basketball"]
deleted_element = sports.splice(2, 0, "volleyball", "rugby")
console.log(sports)
console.log("deleted_element")
console.log(deleted_element)

Output

[ ‘cricket’, ‘football’,‘volleyball’,‘rugby’,‘badminton’,‘basketball’]
deleted_element
[]

The elements are added from index 2 and the rest of the array is shifted to the right. Note that it returns an empty array because deleteCount is set to zero.

The following code uses the splice() method to delete elements.

sports = ["cricket", "football", "badminton", "basketball"]
deleted_element = sports.splice(2, 2)
console.log(sports)
console.log("deleted_element")
console.log(deleted_element)

Output

[ ‘cricket’, ‘football’]
deleted_element
[‘badminton’,‘basketball’]

The first and second parameter shows that 2 elements are to be deleted starting from the index 2 i.e. “badminton” and “basketball”.

Some important notes about the splice() method.

  • If the value of the start parameter is negative, it will start adding/removing elements from the end of the array.
  • If the value of the start parameter is greater than the length of the array, then no elements will be deleted, and the new elements will be added to the end of the array.
  • If the 2nd parameter (deleteCount) is not provided, then no elements will be deleted.
  • If the value of the deleteCount is greater than the length of the remaining elements from the start position, then all elements from the start position will be deleted.

slice()


The slice() method takes out selected elements from the original array and put them into a new array. It does not modify the original array. The syntax is array.slice(start, end). It extracts elements from the start position to the end – 1(inclusive) position. The length of the new array will be end – start. Consider the following examples.

sports = ["cricket", "football", "badminton", "basketball", "volleyball", "rugby"]
new_sports = sports.slice(1, 4)
console.log("new array")
console.log(new_sports)
console.log("original array")
console.log(sports)

Output

new array
[ ‘football’, ‘badminton’, ‘basketball’]
original array
[‘cricket’,‘football’,‘badminton’,‘basketball’,‘volleyball’,‘rugby’]

The elements will be extracted from index 1 to index 3 (inclusive). We can also observe that the original array is not modified.

The parameters start and end can also contain negative values to slice from the end of the array. Let’s see how this works.

sports = ["cricket", "football", "badminton", "basketball", "volleyball", "rugby"]
new_sports = sports.slice(-4, -1)
console.log("new array")
console.log(new_sports)

Output

new array
[ ‘badminton’, ‘basketball’, ‘volleyball’]

It takes out elements form the fourth last position i.e. “badminton” to the 2nd last (Remember end – 1) i.e. “volleyball”.

Note that both parameters are optional. If the start parameter is omitted, it is set to 0 and if the end parameter is omitted, it is set to the length of the array. If only one parameter is provided, it is considered as the start parameter. If both parameters are omitted, the whole array is sliced out.

indexOf()


It returns the index of the element. If the element is present more than once, it will only return the position of the first appearance. The syntax is array.indexOf(el, start), the first parameter represents the element to be found and the second optional parameter represents the starting position of the search (default value = 0). It returns -1 if the element is not found in the given search space.

sports = ["cricket", "football", "badminton", "football", "basketball"]
index = sports.indexOf("football")
console.log("index: " + index)

Output

index: 1

Note that indexOf() method compares element using the === equality operator i.e. the type and content both needs to be the same for two elements to be equal.

lastIndexOf()


This method performs a similar task as indexOf() but it searches the array backward from the starting position(default value = length of the array – 1) i.e. it returns the position of the last appearance.

sports = ["cricket", "football", "badminton", "football", "rugby"]
index = sports.lastIndexOf("football")
console.log("index: " + index)

Output

index: 3

find()


The find() method returns the first element that passes a certain test defined in a callback function. Consider the following example to understand this.

scores = [99, 88, 58, 56, 70]
result = scores.find(testFunction)
console.log(result)
function testFunction(score)
{
    return score >= 80
}

Output

99

What happens is each element of the array is passed to the function one by one until the condition is satisfied. In this example, the search terminates after the first element because it is greater than 80.

Note that it returns undefined if none of the elements satisfy the test condition.

The simpler method is to use the arrow function instead of defining a separate function. i.e.

scores = [99, 88, 58, 56, 70]
result = scores.find(score => score >= 80)
console.log(result)

The output will be the same as above.

The syntax is array.find(function(array value, index, array), thisobject). The first parameter contains the callback function that takes the current array value, index of the current array value (optional), and the array (optional) as arguments. The second optional parameter takes the object that will be used as a this value in the callback function. The default value for the second parameter is undefined.

findIndex()


The find() method returns the value of the first element satisfying a condition, the findIndex() method returns its index. It returns -1 if none of the elements satisfies the test condition. Let’s use the same example as above.

scores = [99, 88, 58, 56, 70]
result = scores.findIndex(score => score >= 80)
console.log(result)

Output

0

The behavior of the findIndex() method is the same as of findIndex() method, but it returns index. As we have seen above, element 99 is the first element that satisfies the condition and its index is 0. Therefore, this method returns 0.

filter()


While the find() method returns only a single element that passes a test, the filter() method returns a new array containing all the elements that satisfy the condition. The syntax is array.filter(function(array value, index, array), thisobject).

scores = [99, 88, 58, 56, 70]
result = scores.filter(score => score >= 80)

Output

[99, 88]

What happens here that the callback function is called for each element regardless if the condition is satisfied once or not. All the elements for which the function returns true are added to the new array. It returns an empty array if none of the elements satisfy the test condition.

map()


The map() method runs a particular function for each element of the array and the return value is stored into a new array. The syntax is array.map(function(array value, index, array), thisobject). The following example takes the square of each element of the array.

numbers = [2, 3, 4, 5, 6]
result = numbers.map(number => number*number)
console.log(result)

Output

[4, 9, 16, 25, 36]

toString()


The toString() method converts an array to a string separated by commas. The syntax is array.toString() and it returns a string.

sports = ["cricket", "football", "badminton", "football", "rugby"]
result = sports.toString()
console.log(result)

Output

cricket,football,badminton,football,rubgy

join()


The join() method is similar to the toString() method except we can provide a separator. The syntax is array.join(separator), the default value of the separator is a comma. Let’s see the example below.

sports = ["cricket", "football", "badminton", "football", "rugby"]
result = sports.join(" ")
console.log(result)

Output

cricket football badminton football rubgy

The above example joins array items into a string separated by spaces.

Note that if the array is empty, then an empty string is returned.

concat()


The concat() method concatenates two or more arrays. The syntax is array1.concat(array2, array3, ….., arrayN). It returns a new array which starts from array1 followed by the arrays given as parameters.

sports1 = ["cricket", "football", "badminton"]
sports2 = ["football", "rugby"]
result = sports1.concat(sports2)
console.log(result)

Output

['cricket', 'football', 'badminton', 'football', 'rubgy']

every()


This method checks if every element in the array passes the test condition given in the callback function. If every element passes the test, it returns true, otherwise, it returns false. The syntax is array.every(function(array value, index, array), thisobject).

some()


While the every() method checks if every element passes the test condition, the some() method checks if any of the elements in the array pass the test condition given in the callback function. It returns true if at least one element satisfies the condition, otherwise, it returns false. The syntax is array.some(function(array value, index, array), thisobject).

includes()


The includes() method finds out if an element is present in the array. It returns true if the element is found, otherwise, it returns false. The syntax is array.includes(el, start). The second optional parameter start represents the position to start the search from. The default value is 0.

sports = ["cricket", "football", "badminton", "rugby"]
result = sports.includes("volleyball")
console.log(result)

Output

false

isArray()


This method checks if an object is an array or not. It returns true if it is an array, otherwise, it returns false. The syntax is Array.isArray(object).

reverse()


As the name suggests, the reverse() method reverses each position of the element of an array, for example, the first element becomes last and the last element becomes first. The syntax is array.reverse(). It returns a new array and modifies the original array as well.

sports = ["cricket", "football", "badminton", "rugby"]
result = sports.reverse()
console.log(result)

Output

['rugby', 'badminton', 'football', 'cricket']

reduce()


The reduce() method requires a callback function that performs operations on each element of an array and reduces the array to a single value. The syntax is array.reduce(function(accumulator, array value, index, array), startValue). The callback function takes four arguments out of which the first two are required. Consider accumulator as a global variable that stores values from the previous function calls. The second parameter startValue(optional) represents the initial value to be stored in the accumulator.

Consider the following example to understand the method. Let’s pass 200 as the startvalue.

marks = [10, 20, 30, 40, 50]
const sum = (accumulator, mark,) => accumulator - mark
result = marks.reduce(sum, 200)
console.log(result)

Output

50

reduceRight()


This method is the same as the reduce() method. However, the elements of the array are passed from right to left (from end to start) in the callback function.

forEach()


The forEach() method runs a callback function for each element of an array. It returns undefined and the syntax is array.forEach(function(array value, index, array), thisobject). This method can be used to iterate through an array. Consider the following example.

sports = ["cricket", "basketball", "football", "rugby"]
sports.forEach(sport => console.log(sport))

Output

cricket
basketball
football
rugby

The above code uses the forEach() method to display each element in the array.

copyWithin()


The copyWithin() method takes parts of an array and copies it in the same array without changing the length. It returns the modified array and changes the original array as well. The syntax is array.copyWithin(target, start, end). The target parameter represents from which position to replace the parts of the array selected from the optional start and end parameters (default value is 0 and array.length, respectively). Let’s see the following example to see how this works.

sports = ["cricket", "basketball", "football", "rugby"]
result = sports.copyWithin(1)
console.log(result)

Output

['cricket', 'cricket', 'basketball', 'football']

In the above example, the parts of the array that will be copied are from start to end i.e. the whole array. The target value represents the elements that need to be copied from index 1. Therefore, the element at index 1 is “cricket”, “basketball” and “football” are at index 2 and 3. The element “rugby” is omitted to keep the length unchanged.

entries()


This method returns a new Array Iterator Object that contains keys as the index and values as the elements of an array. Consider the following example.

sports = ["cricket", "basketball", "football", "rugby"]
result = sports.entries()
console.log(result.next().value)
console.log(result.next().value)
console.log(result.next().value)
console.log(result.next().value)

Output

[0, 'cricket']
[1, 'basketball']
[2, 'football']
[3, ''rugby]

fill()


This method fills elements of an array with a static value. It returns the modified array and changes the original array as well. The syntax is array.fill(val, start, end). The val parameter represents the static value to be replaced from start to end. The start and end parameters are optional (default value is 0 and array.length, respectively). Let’s see.

sports = ["cricket", "basketball", "football", "rugby"]
result = sports.fill("cricket", 0, 3)
console.log(result)
console.log(sports)

Output

['cricket', 'cricket', 'cricket', 'rugby']
['cricket', 'cricket', 'cricket', 'rugby']

from()


The from() method creates an array from an object that has a length property or it is iterable. The syntax is Array.from(object, mapFunction, thisObject). Consider the following example.

sports = "cricket"
result = Array.from(sport)
console.log(result)

Output

['c', 'r', 'i', 'c', 'k', 'e', 't']

keys()


While the entries() method returns an Array Iterator Object that contains keys as the index and values as the elements of an array, the keys() method returns an Array Iterator Object that only contains keys as the index of an array.

sort()


The sort() method arranges elements of an array in alphabetical order by default. It returns the modified array and changes the original array as well. This method works well for strings because it compares the corresponding characters. However, it will provide incorrect results for numbers. For example, when comparing numbers 30 and 120, the method will compare the corresponding digits and will, therefore, put 120 before 30 if sorting in ascending order. However, we know that 30 is less than 120. The syntax is array.sort(callbackFunction). The callback function should return positive, negative, or zero value and it defines a different comparison order. Let’s see.

sports = ["cricket", "basketball", "rugby", "football"]
result = sports.sort()
console.log(result)

Output

['basketball', 'cricket', 'football', 'rugby']

We can use callbackFunction to correctly sort numbers. i.e.

// default array
scores = [30, 220, 20, 150]
incorrect_result = scores.sort()
console.log("incorrect result")
console.log(incorrect_result)
// sort in ascending order
scores = [30, 220, 20, 150]
ascending_result = scores.sort((x, y)=>x-y)
console.log("ascending_result")
console.log(ascending_result)
// sort in descending order
scores = [30, 220, 20, 150]
descending_result = scores.sort((x, y)=y-x)
console.log("descending_result")
console.log(descending_result)

Output

incorrect result
[150, 20, 220, 30]
ascending result
[20, 30, 150, 220]
descending result
[220, 150, 30, 20]

Here is how the callback Function works when sorting numbers in ascending order. When the sort() method compares two values, for example (30, 220), it calls the callback function which subtracts 220 from 30 and the result is negative meaning that 30 is less than 220, so it comes before 220. If the callback function returns a positive value then x > y, so x should come after y. If it returns zero, then the two values are the same and no change is required. The callback function when sorting numbers in descending order just flip the order of subtraction i.e. y – x. Note that the ascending_result.reverse() method can give the same result as well.

valueOf()


The valueOf() method in JavaScript returns the primitive value of the object. In the case of arrays, it returns the value of its elements i.e. the array itself.

That’s it!


Liked the post?
A computer science student having interest in web development. Well versed in Object Oriented Concepts, and its implementation in various projects. Strong grasp of various data structures and algorithms. Excellent problem solving skills.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).