Working with JavaScript Array
- Adds the specified elements to the beginning of an array. Array.prototype.unshift()
- Adds the specified elements to the end of an array. Array.prototype.push()
- Removes the first element from an array. Array.prototype.shift()
- Removes the last element from an array. Array.prototype.pop()
- Iterate through all the elements in an array. Array.prototype.forEach()
- Find index of the first element in an array that satisfies the provided testing function. Array.prototype.findIndex()
- Find the first element in the provided array that satisfies the provided testing function. Array.prototype.find()
- Iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. Array.prototype.findLastIndex()
- Iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. Array.prototype.findLast()
- Filtered down to the elements from the given array that that satisfies the provided testing function. Array.prototype.filter()
- Reverse an array. Array.prototype.reverse()
- Sorts the elements of an array. Array.prototype.sort()
- Returns a shallow copy of a portion of an array into a new array object. Array.prototype.slice()
- Remove or replace existing elements and/or add new elements in an array. Array.prototype.splice()
- To merge two or more arrays. Array.prototype.concat()
- Concatenate all of the elements in an array. Array.prototype.join()
- Determines whether the passed value is an Array. Array.isArray()
Adds the specified elements to the beginning of an array
Array.prototype.unshift()The unshift() method adds the specified elements to the beginning of an array and returns the new length of the array.
const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // Expected output: 5 console.log(array1); // Expected output: Array [4, 5, 1, 2, 3]
Adds the specified elements to the end of an array
Array.prototype.push()The push() method adds the specified elements to the end of an array and returns the new length of the array.
const animals = ['pigs', 'goats', 'sheep']; const count = animals.push('cows'); console.log(count); // Expected output: 4 console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows"] animals.push('chickens', 'cats', 'dogs'); console.log(animals); // Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
Removes the first element from an array
Array.prototype.shift()The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
const array1 = [1, 2, 3]; const firstElement = array1.shift(); console.log(array1); // Expected output: Array [2, 3] console.log(firstElement); // Expected output: 1
Removes the last element from an array
Array.prototype.pop()The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); // Expected output: "tomato" console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); console.log(plants); // Expected output: Array ["broccoli", "cauliflower", "cabbage"]
Iterate through all the elements in an array
Array.prototype.forEach()The forEach() method executes a provided function once for each array element.
const array1 = ['a', 'b', 'c']; array1.forEach((element) => console.log(element)); // Expected output: "a" // Expected output: "b" // Expected output: "c"
Find index of the first element in an array that satisfies the provided testing function
Array.prototype.findIndex()The findIndex() method 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.
See also the find() method, which returns the first element that satisfies the testing function (rather than its index).
const array1 = [5, 12, 8, 130, 44]; const isLargeNumber = ((element) => element > 13); console.log(array1.findIndex(isLargeNumber)); // Expected output: 3 const elementIndex = ((element) => element === 12); console.log(array1.findIndex(elementIndex)); // Expected output: 1
Find the first element in the provided array that satisfies the provided testing function
Array.prototype.find()The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
- If you need the index of the found element in the array, use findIndex().
- If you need to find the index of a value, use indexOf(). (It's similar to findIndex(), but checks each element for equality with the value instead of using a testing function.)
- If you need to find if a value exists in an array, use includes(). Again, it checks each element for equality with the value instead of using a testing function.
- If you need to find if any element satisfies the provided testing function, use some().
const array1 = [5, 12, 8, 130, 44]; const found = array1.find((element) => element > 10); console.log(found); // Expected output: 12
Iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function
Array.prototype.findLastIndex()The findLastIndex() method iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
See also the findLast() method, which returns the value of last element that satisfies the testing function (rather than its index).
const array1 = [5, 12, 50, 130, 44]; const isLargeNumber = (element) => element > 45; console.log(array1.findLastIndex(isLargeNumber)); // Expected output: 3 // Index of element with value: 130
Iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function
Array.prototype.findLast()The findLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, undefined is returned.
If you need to find:
- the first element that matches, use find().
- the index of the last matching element in the array, use findLastIndex().
- the index of a value, use indexOf(). (It's similar to findIndex(), but checks each element for equality with the value instead of using a testing function.)
- whether a value exists in an array, use includes(). Again, it checks each element for equality with the value instead of using a testing function. if any element satisfies the provided testing function, use some().
const array1 = [5, 12, 50, 130, 44]; const found = array1.findLast((element) => element > 45); console.log(found); // Expected output: 130
Filtered down to the elements from the given array that that satisfies the provided testing function
Array.prototype.filter()The filter() method 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.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter((word) => word.length > 6); console.log(result); // Expected output: Array ["exuberant", "destruction", "present"]
Reverse an array
Array.prototype.reverse()The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
To reverse the elements in an array without mutating the original array, use toReversed().
const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // Expected output: "array1:" Array ["one", "two", "three"] const reversed = array1.reverse(); console.log('reversed:', reversed); // Expected output: "reversed:" Array ["three", "two", "one"] // Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // Expected output: "array1:" Array ["three", "two", "one"]
Sorts the elements of an array
Array.prototype.sort()The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
To sort the elements in an array without mutating the original array, use toSorted().
const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // Expected output: Array ["Dec", "Feb", "Jan", "March"] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // Expected output: Array [1, 100000, 21, 30, 4]
Returns a shallow copy of a portion of an array into a new array object
Array.prototype.slice()The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // Expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // Expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // Expected output: Array ["bison", "camel", "duck", "elephant"] console.log(animals.slice(-2)); // Expected output: Array ["duck", "elephant"] console.log(animals.slice(2, -1)); // Expected output: Array ["camel", "duck"] console.log(animals.slice()); // Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
Remove or replace existing elements and/or add new elements in an array
Array.prototype.splice()The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
To create a new array with a segment removed and/or replaced without mutating the original array, use toSpliced(). To access part of an array without modifying it, see slice().
const months = ['Jan', 'March', 'April', 'June']; months.splice(1, 0, 'Feb'); // Inserts at index 1 console.log(months); // Expected output: Array ["Jan", "Feb", "March", "April", "June"] months.splice(4, 1, 'May'); // Replaces 1 element at index 4 console.log(months); // Expected output: Array ["Jan", "Feb", "March", "April", "May"]
To merge two or more arrays
Array.prototype.concat()The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // Expected output: Array ["a", "b", "c", "d", "e", "f"]
Concatenate all of the elements in an array
Array.prototype.join()The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
const elements = ['Fire', 'Air', 'Water']; console.log(elements.join()); // Expected output: "Fire,Air,Water" console.log(elements.join('')); // Expected output: "FireAirWater" console.log(elements.join('-')); // Expected output: "Fire-Air-Water"
Determines whether the passed value is an Array
Array.isArray()The Array.isArray() static method determines whether the passed value is an Array.
console.log(Array.isArray([1, 3, 5])); // Expected output: true console.log(Array.isArray('[]')); // Expected output: false console.log(Array.isArray(new Array(5))); // Expected output: true console.log(Array.isArray(new Int16Array([15, 33]))); // Expected output: false console.log(Array.isArray("raj")); // Expected output: false console.log(Array.isArray([])); // Expected output: true