Hello! In this article, I'm going to give a short description and quick examples of some array methods in JS.
Overview
Arrays are used to store multiple values in a single variable. This is compared to a variable that can store only one value. Each item in an array has a number attached to it, called a numeric index, that allows you to access it. In JavaScript, arrays start at index zero and can be manipulated with various methods.
at()
- The method takes an integer value and returns an item at that index, allowing for positive an negative integers.
Example
[2, 3, 4, 5].at(1) //--> 3
push()
- The method adds one or more to the end of an array and it returns the new length of an array.
Example:
[2, 3, 4, 5].push(6) //--> [2, 3, 4, 5, 6]
pop()
- It removes the last element of an array and returns that element. The method changes the length of an array.
Example:
[2, 3, 4, 5].pop() //--> [2, 3, 4]
fill()
- Changes all elements in an array to a static value from a start index (0) to an end index (arr.length). Returns the modified array.
Example:
[2, 3, 4, 5].fill(1) //--> [1, 1, 1]
join()
- Creates and returns a new string by concatenating all of the elements in an array, seperated by a comma or any specified seperator string.
Example:
[2, 3, 4, 5].join('') //--> '2345' (string)
shift()
- Removes the first element of an array and returns that removed element.
Example:
[2, 3, 4, 5].shift() //--> [3, 4, 5]
reverse()
- Elements in an array will be turned towards the direction opposite to that previously stated.
Example:
[2, 3, 4, 5].reverse() //--> [5, 4, 3, 2]
unshift()
- Adds one or more elements to the beginning of an array.
Example:
[2, 3, 4, 5].unshift(1) //--> [1, 2, 3, 4, 5]
includes()
- Determines whether an array includes a certain value among its entries, returning true or false.
Example:
[2, 3, 4, 5].includes(4) //--> true
map()
- Creates a new array by calling a function for every array element.
Example:
[2, 3, 4, 5].map(item => 2 * item) //--> [4, 6, 8, 10]
filter()
- Creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
Example:
[2, 3, 4, 5].filter(item => item > 3) //--> [4, 5]
find()
- Used to get the value of the first element in an array that satisfies the provided condition.
Example:
[2, 3, 4, 5].find(item => item > 3) //--> 4 (first match)
every()
- Tests whether all elements in an array pass the test implemented by the provided function and returns a boolean.
Example:
[2, 3, 4, 5].every(item => item > 0) //--> true
findIndex()
- Returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
Example:
[2, 3, 4, 5].findIndex(item => item === 3) //--> 1
That's it!! #HappyCoding
PS: Watch out for Episode 2 of Array methods soon!
Cheers.
Top comments (0)