Arrays are special objects in JavaScript that we use to store collections of values. JavaScript offers several built-in methods and properties that allow us to manipulate the arrays. In this tutorial, let us explore all the JavaScript array methods with an example of each.
Table of Contents
Array Methods
Following are all the methods available on arrays in JavaScript
Check if it is an Array
IsArray
The IsArray method allows you to check whether a given value is an array. It returns a true
if the value is an array and a false
if it is not.
IsArray is the preferred method over instanceOf
because it works across realms.
isArray method added in the ES5 version of JavaScript. Hence will not work in older browsers.
The code below uses the isArray method to check if the given value is an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | let arr = [1,2,3] console.log(Array.isArray(arr)); //true arr = new Array(5) console.log(Array.isArray(arr)); //true let obj= {} console.log(Array.isArray(obj)); //false //Typed Arrays are not arrays. They are objects let int16Arr = new Int16Array(2); console.log(Array.isArray(int16Arr)); //false |
Create Array
from
The Array from
method creates a new array from an iterable object or array-like object.
An “iterable object” is anything we can iterate over item by item. For example, arrays, objects, and strings are iterable in JavaScript.
An array-like object is an object which looks like an array but is not an array.
An object, if it has
- indexed elements (i.e., the object has sequential access to its properties);
- has a length property.
For Example, the arrLike object below looks like an array with integer property names and a length property
1 2 3 4 5 6 | const arrLike = { 0: 'foo', 1: 'boo', 2: 'koo', length: 3 }; console.log(arrLike[0]) //foo console.log(arrLike.length) //3 |
We can easily convert array-like objects using the from
method.
1 2 3 4 5 6 7 8 9 10 | const arrLike = { 0: 'foo', 1: 'boo', 2: 'koo', length: 3 }; console.log(Array.isArray(arrLike)) //false let arr = Array.from(arrLike) console.log(Array.isArray(arr)) //true console.log(arr) //[ 'foo', 'boo', 'koo' ] |
You can read more from the tutorial array from in Javascript.
of
The of is a static method that creates a new Array instance from the arguments we pass to it, regardless of the number or type of the arguments.
The syntax of of method is as follows
1 2 3 | Array.of(element0, element1, /* … ,*/ elementN) |
Examples of array of method.
1 2 3 4 5 6 7 8 9 10 | arr = Array.of('foo', 2, 'bar', true) console.log(arr); //[ 'foo', 2, 'bar', true ] arr = Array.of(2) console.log(arr); //[2] arr = Array.of() console.log(arr); //[] |
It is very similar to an Array constructor, with one difference. The new Array(5) will create an array with five empty elements, while Array.of(5) will create an array with one element of value 5
1 2 3 4 5 6 7 | arr= new Array(5) console.log(arr) //[ <5 empty items> ] arr = Array.of(5) console.log(arr); //[5] |
Read Values
at
The at
method allows us to read an element from the array. It takes an integer (both positive and negative) value and returns the element at that index. The array is read backward from the end if we provide a negative integer.
In the code below, arr.at(1)
reads the value at index 1. While arr.at(-1)
will read the value at index four i.e, (arr.length-1)
1 2 3 4 5 | const arr = [1, 2, 3, 4, 5]; console.log(arr.at(1)) //2 Value at index 1 console.log(arr.at(-1)) //5 Value at index 4 (5 - 1) |
Add/Remove/Modify elements
push
The array push method adds new elements to the end of an array. It takes the element to be added as an argument and returns the array’s new length. This method can push scalar values, objects, or another array to an array.
Syntax of the push method is as follows
1 2 3 | push(element0, element1, /* … ,*/ elementN) |
Here element0, element1, …, elementN
are the elements you want to add to the end of the array. You can provide any number of items separated by a comma.
The following example, appends multiple elements to the array by supplying multiple items separated by a comma to the push method.
1 2 3 4 5 6 | let numbers=[1,2,3,4] numbers.push(5,6,7) //pushing 5,6,7 to numbers array console.log(numbers) //[ 1, 2, 3, 4, 5, 6, 7 ] |
array push method in JavaScript
pop
The pop method removes and returns the array’s last element. If the array is empty, it will do nothing but return undefined.
It mutates the array and changes its length.
Syntax of the array.pop method is follows
1 2 3 | array.pop() |
In the following code. we create an array of numbers and then call the pop() method on it. The method removes the last element from the array, the number 5, and returns its value. We store the returned value in a variable named lastNumber. Finally, we log the modified array and the removed value to the console.
1 2 3 4 5 6 | let numbers = [1, 2, 3, 4, 5]; let lastNumber = numbers.pop(); console.log(numbers); // [1, 2, 3, 4] console.log(lastNumber); // 5 |
You can read more about from the tutorial array pop method in JavaScript
unshift
The array Unshift method is a built-in JavaScript method that adds new elements to the beginning of an array. It takes the element to be added as an argument and returns the array’s new length. This method can insert scalar values, objects, or another array into an array.
The syntax for the unshift() method is as follows:
1 2 3 | array.unshift(element0, element1, /* … ,*/ elementN) |
Here, the array is the array to which we want to add elements, and element1
, element2
, …, and elementN
are the elements we want to add to the beginning of the array. Note that this method can add as many elements as we want.
The code below inserts multiple elements to the numbers array.
1 2 3 4 5 6 7 8 9 10 | let numbers=[5,6,7] //inserting multiple items at the start of numbers array numbers.unshift(1,2,3,4) console.log(numbers) //[ 1, 2, 3, 4, 5, 6, 7 ] |
shift
The array shift method removes and returns the first element from the array. If the array is empty, it will do nothing but return undefined.
It mutates the array and changes its length.
The syntax of the array.shift
method is as follows:
1 2 3 | array.shift() |
It does not take any arguments.
In the following example, we have an array of numbers. We call the shift method on it. It removes the first element, number 1, from the array and returns its value.
1 2 3 4 5 6 | let numbers = [1, 2, 3, 4, 5]; let removedValue = numbers.shift(); console.log(numbers); // [ 2, 3, 4, 5 ] console.log(removedValue); // 1 |
You’ll be able to read more about the tutorial array shift in Javascript.
splice
The splice method removes or replaces existing elements with new elements in an array. We can also insert new elements at any specific location in the array.
Syntax of the splice method as follows
1 2 3 | splice(start, deleteCount, item1, item2, itemN) |
The splice method usually accepts three arguments
- The start is the index of the array where we start changing the array.
- deleteCount is the number of items to be removed from the start index
- item1, item2, itemN, etc., are the elements to add to the array at the index start
The code below inserts the value 4 at index 3. It will remove 0 any elements from the array.
1 2 3 4 5 6 7 8 | let numbers = [1, 2, 3, 5, 6 ]; // Start 3 Number of elements to delete= 0 items to insert 4 numbers.splice(3,0,4); console.log(numbers); // [1,2,3,4,5,6] |
The following code inserts 9,10 & 11 at index location 3. It also removes the three elements starting from location 3.
1 2 3 4 5 6 7 8 | let numbers = [1, 2, 3, 5, 6 ]; //start=3 Number of elements to delete= 3 items to insert 9, 10, 11 numbers.splice(3 ,3, 9,10,11); console.log(numbers); // [ 1, 2, 3, 9, 10, 11 ] |
The code below removes the two items from the array starting from index 2.
1 2 3 4 5 6 7 8 | let numbers = [0, 1, 2, 3, 4, 5]; // it will remove two items starting from the index 2 ( 2 & 3) numbers.splice(2,2); console.log(numbers) //[ 0, 1, 4, 5 ] |
CopyWithin
The copyWithin method is a built-in method that allows us to copy a sequence of elements within an array to another location within the same array, overwriting any existing elements.
copyWithin does not change the length of the array. It copies the elements until the end of the array.length
. It will discard anything beyond the array.length
.
The syntax for the copyWithin method is as follows.
1 2 3 | Array.copyWithin(target, start, end) |
Where the target is the index of the element to copy the sequence to, the start is the index of the first element to copy from, and the end is the index of the last element to copy from (but not including).
If any of the argument is a negative integer, the index counts backward from the array’s end.
In this example, we start with an array [1, 2, 3, 4, 5]
, and we want to copy the sequence of items from index 0 to 1 (2 elements) to index 3 & 4.
Hence, we invoke the copyWithin(3, 0,2)
.
Here 2 is the target
, and 0 is the index of the first element. The 2 is the value of the end
argument, which is the following index after the end of the sequence, so we copy two elements in total.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | let numArr = [1, 2, 3, 4, 5]; // target=3 start =0 end = 2 // Copies 2 element from index 0 & 1 to index 3 & 4 numArr.copyWithin(3, 0,2); console.log(numArr); //output //[ 1, 2, 3, 1, 2 ] // Value 1 from index 0 is now copied to index 3 // Value 2 from index 1 is now copied to index 4 // Values at target locations are overwritten |
You can refer to the article copyWithin in Javascript
fill
The array fill method allows you to set the elements of an array to a specific value.
Syntax of the fill method as follows
1 2 3 | fill(value, start, end) |
The value parameter is the value that you want to fill the array with.
The start is the starting index from where you’d like to fill the array. It is optional and defaults to index 0.
The end is the ending index up to which you want to fill. It is optional and defaults to the array’s last index (array.length – 1) if omitted.
The start and end can have negative values. In that case, it will count back from the array’s end.
The code below creates a new array from the array constructor function. It will then fills it up with 0 value
1 2 3 4 5 | const arr = new Array(5); arr.fill(0); console.log(arr); // Output: [0, 0, 0, 0, 0] |
The code below fills up the portion of the array using fill method.
1 2 3 4 5 6 7 8 | const arr = [1, 2, 3, 4, 5]; // fill from index 2 to index 4 with value 0 arr.fill(0, 2, 4); console.log(arr); // Output: [1, 2, 0, 0, 5] |
Sorting Arrays
sort
The sort method accepts a callback function as an argument and sorts the array using that function. The callback function (known as compareFn
) is optional. The sort method will use the default sort if we omit the callback function. The default sorting method converts each element into strings (casts them to strings) and compares their values according to the UTF-16 encoding standard.
The syntax of the sort() method is as follows:
1 2 3 | array.sort([compareFn]) |
The following code sorts the array of numbers. As you can see from the output, 7000 has come before 2000, 21 & 5 because the default sort method converts numbers to strings and then sorts them in ascending order.
1 2 3 4 5 6 | const numbers = [1, 300, 7000, 2000, 21, 5]; numbers.sort(); console.log(numbers); //[ 1, 2000, 21, 300, 5, 7000 ] |
To customize the sorting order, we need to provide the compare function. The syntax of which is as follows.
1 2 3 | compareFn(a, b) |
The compareFn
accepts two parameters, a
and b
, corresponding to the two elements of the array that we are comparing. A positive return value will sort a
after b
, a negative value will sort b
after a
, and 0 will keep the original order.
The code below sorts the numbers array in ascending order using the sortNumbers
callback function.
1 2 3 4 5 6 7 8 9 10 | const numbers = [1, 300, 7000, 2000, 21, 5]; numbers.sort(sortNumbers); console.log(numbers); //[ 1, 5, 21, 300, 2000, 7000] function sortNumbers(a, b) { return a - b; } |
instead of separate function, you can make use of arrow function.
1 2 3 4 5 6 | const numbers = [1, 300, 7000, 2000, 21, 5 ]; numbers.sort((a,b) => a - b); console.log(numbers); //[ 1, 5, 21, 300, 2000, 7000] |
You can learn more about how to sort arrays in JavaScript.
reverse
The reverse method reverses the order of the elements in an array. It moves first element to last, the second to second last, and so on.
The syntax for the reverse method is as follows:
1 2 3 | array.reverse() |
The reverse
method mutates the original array, meaning it modifies the array in place and returns a reference to the same array with the reversed order of elements.
The following example shows how to use the reverse
method on an array.
1 2 3 4 5 6 | const arr = [1, 2, 3, 4, 5]; arr.reverse(); console.log(arr); //[ 5, 4, 3, 2, 1 ] |
Merge & Split Arrays
concat
The concat method combines two or more arrays into a new single array and then returns that array. It does not change the original array but returns a new array.
The syntax for the concat() method is as follows:
1 2 3 | array.concat(value0, value1, /* … ,*/ valueN) |
array is the original array that you want to join with other arrays or values.
The value is the value we want to merge with the original array. It can be an array or just any value. The concat will create a shallow copy of the original array if we omit the values.
The concat will not change the original array. It will always return the new array.
In this example, we create two arrays, numArr1, and numArr2 and then use the concat method to combine them into a new array called numbers.
1 2 3 4 5 6 7 | const numArr1 = [1, 2, 3]; const numArr2 = [4, 5, 6]; const numbers = numArr1.concat(numArr2); console.log(numbers); |
The code below merges two arrays and a few numbers into a new array.
1 2 3 4 5 6 7 8 | const numArr1 = [1, 2, 3]; const numArr2 = [4, 5, 6]; const numbers = [].concat(numArr1, numArr2, 7, 8, 9 ); console.log(numbers); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] |
Slice
The slice method extracts a portion of an existing array and returns it as a new array.
The syntax of the slice method is as follows.
1 2 3 | Array.slice(start, end) |
Where start is the starting index, and the end is the ending index of the array section we want to extract.
Slice creates a new array that contains all the elements from the start
index up to the end -1
index. Note that it will not copy the element at the end
index.
If we omit the start
, it will default to 0. If we omit the end
, it will default to array.length
.
The code below copies the elements from the index 0 to 3 to a new array.
1 2 3 4 5 | const numArr = [1, 2, 3, 4, 5]; const newArray = numArr.slice(0,3); console.log(newArray); // [1, 2, 3] |
The code below copies everything from the original array to the new array. The numArr.slice()
is equivalent to numArr.slice(0,numArr.length)
;
1 2 3 4 5 6 7 | const numArr = [1, 2, 3, 4, 5]; const newArray = numArr.slice(); //The above code is the same as //const newArray = numArr.slice(0, numArr.length); console.log(newArray); // [ 1, 2, 3, 4, 5 ] |
Flatten Array
Join
The join method joins the elements of an array into a string.
If the array has only one item, it will return it.
If the array has more than one item, it will concatenate each element separated by a separator and returns it.
We can specify the separator as the first argument.
It will treat undefined, null, and empty slots as empty strings.
Syntax
1 2 3 | array.join(separator) |
Where the separator is the separator that you wish to use, if omitted, it will use the comma.
The following example creates an array of fruits. It shows how you can use the join statement to convert them into a string.
1 2 3 4 5 6 7 8 9 10 11 12 | const fruits = ['Apple', 'Oranage', 'Banana']; console.log(fruits.join()); //Apple,Oranage,Banana console.log(fruits.join('')); // AppleOranageBanana console.log(fruits.join('-')); // Apple-Oranage-Banana |
flat
The flat method lets us flatten a nested array into an array of single dimensions.
The syntax for using the flat is as follows.
1 2 3 | array.flat([depth]) |
Where array is the array we want to flatten.
The depth is an optional argument that specifies the maximum nesting depth to flatten.
For example, if we set the depth as 2, the flat will flatten nested arrays until depth 2. nested arrays beyond depth 2 will return unchanged.
If we omit the depth, it will default to 1.
If the depth is 0, the flat method will return the original array unchanged.
In the code below, the nestedArray is an array with depth 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //Array nested upto depth 2 const nestedArray = [1, [2, 3], [[4], [5, 6]]]; //More examples //depth 1 (default) flattenedArray = nestedArray.flat(); console.log(flattenedArray); // [ 1, 2, 3, [ 4 ], [ 5, 6 ] ] //depth 1. Same as above flattenedArray = nestedArray.flat(1); console.log(flattenedArray); // [ 1, 2, 3, [ 4 ], [ 5, 6 ] ] //depth 0. retuns unchanged flattenedArray = nestedArray.flat(0); console.log(flattenedArray); // [ 1, [ 2, 3 ], [ [ 4 ], [ 5, 6 ] ] ] //depth 2. Flattens upto depth 2 flattenedArray = nestedArray.flat(2); console.log(flattenedArray); // [ 1, 2, 3, 4, 5, 6 ] //-ve depth same as depth 0 flattenedArray = nestedArray.flat(-1); console.log(flattenedArray); // [ 1, [ 2, 3 ], [ [ 4 ], [ 5, 6 ] ] ] |
flatMap
The flatMap method transforms the original array using a map function and then flattens it to the depth of 1.
The flatMap iterates over an array, execute a provided map function once for every array element, and uses the result to create a new array. It then flattens the array to a depth of 1.
It is similar to the calling map method followed by the flat method with a depth of 1. But it is slightly more efficient than calling those two methods separately.
The syntax of flatMap is as follows:
1 2 3 | flatMap(callbackFn, thisArg) |
The flatMap method takes in two optional parameters
callbackFn- A function that flatMap invokes for each element of the array. The callback function returns an array, then flattened and concatenated with the output array. This function takes up to three arguments (element, index, array). The syntax is as follows
1 2 3 | callbackFn(element, index, array) |
The element
parameter is the current element being processed, the index
parameter is the current element’s index, and the array
parameter is the array being processed.
thisArg – An optional parameter that specifies the value to be used as this when executing the callback function.
The code below contains array of numbers. The callback function multiplies each element by 2 and returns the array, which is then flattened
1 2 3 4 5 6 | const arr = [1, 2, 3, 4]; const flattened =arr.flatMap((x) => [x * 2]); console.log(flattened) // [2, 4, 6, 8] |
Search
indexOf
The indexOf
method searches for a given element within a given array. It starts searching for the items from index 0 and returns the index of the first occurrence of the given element in the array. If the element does not exist, then it will return -1.
The syntax of the indexOf
method is as follows:
1 2 3 | indexOf(element, startIndex) |
Where element
is the element to be searched in the array, and startIndex
is the optional index from which to start the search.
If the startIndex
is negative, the search will start from the
. i.e., it will count back from the end of the arraystartIndex
+ array.length
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const arr = [1, 2, 3, 4, 5, 6]; //Search for 2 console.log(arr.indexOf(3)); //2 //Start search from index 2 console.log(arr.indexOf(3,2)); //2 //Start search from index 4 console.log(arr.indexOf(3,4)); //-1 //Start search from index 2 (becuase 6-4=2) console.log(arr.indexOf(3,-4)); //2 |
LastIndexOf
The lastIndexOf
method searches for a given element within a given array. It starts searching for the item from the last index of the array and searches backward. Hence it returns the index of the last occurrence of the given element. If the element does not exist, then it will return -1.
The syntax of the lastIndex is as follows
1 2 3 | lastIndexOf(element, fromIndex) |
The element
is the element to be searched in the array, and fromIndex
is the optional index from which to start the search. Note that the search will begin from fromIndex
and searches backwards until the index 0
.
If the fromIndex
is negative, the search will start from the fromIndex + array.length
. i.e., it will count back from the end of the array
1 2 3 4 5 6 7 8 9 10 11 | const fruits = ['apple', 'banana', 'orange', 'apple', 'pear']; //start search from index array.length-1 i.e.4 lastIndex = fruits.lastIndexOf('apple'); console.log(lastIndex); //3 //start search from index 2. Hence returns 0 lastIndex = fruits.lastIndexOf('apple',2); console.log(lastIndex); //0 |
includes
The includes
method checks if a certain element exists in the array. If it exists, it returns true
else, false
.
The syntax of includes method is as follows.
1 2 3 | includes(searchElement, fromIndex) |
The searchElement
is the element to be searched in the array, and fromIndex
is the optional index from which to start the search.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const arr = [1, 2, 3, 4, 5, 6]; //Search for 2 console.log(arr.includes(3)); //true //Start search from index 2 console.log(arr.includes(3,2)); //true //Start search from index 4 console.log(arr.includes(3,4)); //false //Start search from index 2 (becuase 6-4=2) console.log(arr.includes(3,-4)); //true |
find
The find method searches elements in the array using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the first element that matches the criteria. Else returns undefined.
The syntax of the find method is as follows.
1 2 3 | find(callbackFn, thisArg) |
Where callbackFn is a function that find method invokes for each element of the array. It will contain the logic to check elements of the array. The callbackFn takes up to three arguments (element, index, array) and must return true if the element matches the search criteria.
In the code below, we have an array of fruits. We are using the find() method to search for the element ‘mango’. The findLogic is the callback function, which returns true if the value of the element is mango and else false.
1 2 3 4 5 6 7 8 9 10 | const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya']; const result = fruits.find(findLogic); console.log(result); //mango function findLogic(element) { if (element==='mango') return true return false } |
You can also use an arrow function.
1 2 3 4 5 | const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya']; const result = fruits.find(fruit => fruit === 'mango'); console.log(result); //mango |
findIndex
The findIndex
method searches elements in the array using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the index of the first element that matches the criteria. Else returns -1.
The findIndex
is the same as the find
method. The only difference is that the find
returns the value of the element while findIndex
returns its index.
The syntax of the findIndex
is as follows.
1 2 3 | findIndex(callbackFn, thisArg) |
Example of findIndex
1 2 3 4 5 | const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya']; const result = fruits.findIndex(fruit => fruit === 'mango'); console.log(result); //2 |
findLast
The findLast method searches elements in the array in reverse order using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the first element that matches the criteria. Else returns undefined.
findLast
is similar to the find method. The find
method searches from the beginning of the array, and the findLast
searches from the end of the array.
The syntax of the findLast
method is as follows.
1 2 3 | findLast(callbackFn, thisArg) |
The following is an example of the findLast
method.
1 2 3 4 5 | const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya']; const result = fruits.findLast(fruit => fruit === 'mango'); console.log(result); //mango |
findLastIndex
The findLastIndex is similar to the findLast method. It searches elements in the array in reverse order using search criteria and checks if any element satisfies that criterion. If a match is found, it returns the index of the element that matches the criteria. Else returns -1
The findLast returns the matching element, while findLastIndex returns the index of the matching element.
The syntax of the findLastIndex method is as follows.
1 2 3 | findLastIndex(callbackFn, thisArg) |
The following is an example of the findLastIndex method.
1 2 3 4 5 | const fruits = ['apple', 'banana', 'mango', 'orange', 'papaya']; const result = fruits.findLastIndex(fruit => fruit === 'mango'); console.log(result); //2 |
Loop
forEach
The forEach
method iterates over an array and executes a provided function once for every array element.
forEach
method can be used as an alternative to looping statements like for, for…of, and for…in.
The syntax of forEach
is as follows.
1 2 3 | forEach(callbackFn, thisArg) |
callbackFn- A function that forEach
method invokes for each element of the array. The callbackFn
takes up to three arguments (element
, index
, array
). The syntax is as follows.
1 2 3 | callbackFn(element, index, array) |
The element
parameter is the current element being processed, the index
parameter is the current element’s index, and the array
parameter is the array being processed.
In this code, we declare an anonymous callback function that simply logs each element to the console.
1 2 3 4 5 6 7 | let myArray = [1, 2, 3, 4, 5]; myArray.forEach(function(element) { console.log(element); }); //1 2 3 4 5 |
entries
The entries method allows us to create an iterator object from an array containing each index’s key/value pairs.
Each key-value pair the entries method returns is an array with two elements. The first element is the index number, and the second is its corresponding value.
The syntax of the entries method is as follows.
1 2 3 | entries() |
The code below uses the for of loop to iterate over iterated returned by the entries method. The element in the array is “a” and its index position is 0. Hence the iterator returns [ 0, ‘a’ ]
1 2 3 4 5 6 7 8 9 10 11 | const a = ["a", "b", "c"]; for (const e of a.entries()) { console.log(e); } //[ 0, 'a' ] //[ 1, 'b' ] //[ 2, 'c' ] |
Values
The values method allows us to create an iterator object from an array containing the values of each element in an array in the order they appear.
It is similar to entries method, but only returns the values. The keys method returns the only keys.
The syntax of the values method is as follows
1 2 3 | values() |
Example
1 2 3 4 5 6 7 8 9 10 11 | const a = ["a", "b", "c"]; for (const e of a.values()) { console.log(e); } //a //b //c |
keys
The Keys method allows us to create an iterator object from an array containing the keys of each element in an array in the order they appear.
It is similar to entries method, but only returns only the keys. It is also similar to values method, which only returns values.
The syntax of the values method is as follows
1 2 3 | keys() |
Example
1 2 3 4 5 6 7 8 9 10 11 | const a = ["a", "b", "c"]; for (const e of a.keys()) { console.log(e); } //0 //1 //2 |
Transform an Array
map
The array map method allows us to create a new array by transforming each element of an existing array using a callback function. It iterates over each element of an array, invokes the callback function, and uses the result to create a new array.
The Syntax of the map method is as follows.
1 2 3 | array.map(callbackFn , thisArg) |
The callbackFn
is the callback function invoked against each element of the existing array.
thisArg
is an optional value that becomes the this of executing the callback function.
The Syntax of the callbackFn
is as follows.
1 2 3 | callbackFn(currentValue, index, array) |
Where the currentValue
is the current element being processed by the map
method. Index
(optional) is the current element’s index, and array
(optional) is the array being processed.
The code below creates a new array doubledNumbers
by multiplying each element of the existing array by two.
1 2 3 4 5 | const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); console.log(doubledNumbers); |
Filter
Array filter allows us to create a new array by filtering out the elements of a given array. It does that by using a filter function. The filter method iterates over every array element and executes the filter function. It will create a new array with all elements that pass the filter function.
The Syntax of the Javascript filter method is as follows.
1 2 3 | array.filter(filterFn, thisArg) |
The filterFn is the callback function invoked against each element of the existing array. It must return true or false.
thisArg is an optional value that becomes the this of executing the filterFn function.
The Syntax of the callbackFn is as follows.
1 2 3 | filterFn(currentValue, index, array) |
The currentValue is the current element of the array being processed by the filter method. Index (optional) is the current element’s index, and array (optional) is the array.
The filter method in the following example takes in a number and returns true if the number is odd. The filter method then returns a new array containing only the odd numbers.
1 2 3 4 5 | const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12]; const oddNumArr = numArr.filter((num) => num % 2 !== 0); console.log(oddNumArr); // [1, 3, 5, 7, 9, 11] |
Misc
reduce
The reduce method reduces the array to a single value. It iterates over each element of the array and invokes a callback function. The callback function (the reducer function) returns a single output value.
The syntax of the reduce method is as follows.
1 2 3 | reduce(reducerFn, initialValue) |
The reducer function (reducerFn) takes four arguments. The first two arguments are the accumulator and the current value of the array. It returns the updated value of the accumulator, which it will use as the accumulator for the next iteration.
An initialValue is optional and is the initial value of the accumulator. If no value is specified, it will use the first element of the array as the initial value.
The syntax of the reducer function is as follows.
1 2 3 | function (accumulator, currentValue, currentIndex, array) |
The code below uses the reduce method to calculate the sum of all the elements of a numbers array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const numArr = [1, 2, 3, 4, 5]; sum = numArr.reduce((accumulator, currentValue) => { return accumulator + currentValue; }); console.log(sum); // Output: 15 //with initial value sum = numArr.reduce((accumulator, currentValue) => { return accumulator + currentValue; },10); console.log(sum); // Output: 25 |
reduceRight
The reduceRight method reduces the array to a single value. It iterates over each array element in descending-index order and invokes a callback function. The callback function (the reducer function) returns a single output value.
The reduceRight is similar to the reduce method. The only difference is that it iterates array in descending order
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const numArr = [1, 2, 3, 4, 5]; sum = numArr.reduceRight((accumulator, currentValue) => { return accumulator + currentValue; }); console.log(sum); // Output: 15 //with initial value sum = numArr.reduceRight((accumulator, currentValue) => { return accumulator + currentValue; },10); console.log(sum); // Output: 25 |
every
Every method tests to see if all elements in an array pass a particular test. It invokes the callback function on every element of the array. If callback returns true for every element, then the method will return true else, false
The syntax of every method is as follows:
1 2 3 | every(callbackFn, thisArg) |
callbackFn
is the callback function that the Every method will invoke against each array element.
ThisArg
is an optional parameter specifying the value to be used for this when executing the callback function.
The syntax of the callbackFn is as follows:
1 2 3 | callbackFn(element, index, array) |
Where
Element
is the current element being processed in the array.
Index
(optional) is the index of the current element being processed.
Array
(optional) is the array that every() was called upon.
1 2 3 4 5 6 7 8 | const numArr = [1, 2, 3, 4, 5]; result = numArr.every((e) => { return e > 0; }); console.log(result); //true |
1 2 3 4 5 6 7 | const numArr = [1, 2, 3, 4, 5]; result = numArr.every((e) => { return e > 3; }); console.log(result); //false |
some
Some method tests to see if at least one element in an array pass a particular test. It invokes the callbackFn function on every element of the array. If callBackFn returns true for any one of the element, then the method will return true else, false.
The syntax of every method is as follows:
1 2 3 | some(callbackFn, thisArg) |
The syntax is similar to every method
1 2 3 4 5 6 7 8 9 10 11 12 13 | const numArr = [1, 2, 3, 4, 5]; result = numArr.some((e) => { return e > 3; }); console.log(result); //true result = numArr.some((e) => { return e > 5; }); console.log(result); //false |
Array Properties
Length
The array length property of the JavaScript array returns the number of elements the array can hold. The length also includes the number of elements plus empty slots (in the case of sparse arrays), if any, in that array. We can also use the length property to increase or shorten the array’s length
1 2 3 4 5 6 | //Example const books = ["Ulysses", "Don Quixote", "War and Peace", "Moby Dick"]; console.log(books.length) //4 |