Array Methods - rs-hash/Learning GitHub Wiki
Below is a list of all array instance methods in JavaScript along with examples:
-
concat()- Description: Joins two or more arrays and returns a new array without modifying the original arrays.
- Example:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combinedArray = array1.concat(array2); // Output: [1, 2, 3, 4, 5, 6]
-
copyWithin()- Description: Copies a sequence of elements within an array to another location in the same array, overwriting existing values.
- Example:
const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']; fruits.copyWithin(2, 0, 2); // Output: ['apple', 'banana', 'apple', 'banana', 'kiwi']
-
entries()- Description: Returns a new Array Iterator object that contains the key-value pairs for each index in the array.
- Example:
const fruits = ['apple', 'banana', 'orange']; const iterator = fruits.entries(); for (const [index, value] of iterator) { console.log(index, value); } // Output: 0 apple, 1 banana, 2 orange
-
every()- Description: Tests whether all elements in the array pass the provided test function, returning
trueorfalse. - Example:
const numbers = [2, 4, 6, 8, 10]; const allEven = numbers.every(num => num % 2 === 0); // Output: true
- Description: Tests whether all elements in the array pass the provided test function, returning
-
fill()- Description: Fills all elements of an array with a static value, optionally specifying start and end positions.
- Example:
const numbers = [1, 2, 3, 4, 5]; numbers.fill(0, 1, 3); // Output: [1, 0, 0, 4, 5]
-
filter()- Description: Creates a new array with elements that pass the provided test function.
- Example:
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); // Output: [2, 4]
-
find()- Description: Returns the first element in the array that satisfies the provided test function, or
undefinedif no element is found. - Example:
const numbers = [1, 2, 3, 4, 5]; const foundNumber = numbers.find(num => num > 3); // Output: 4
- Description: Returns the first element in the array that satisfies the provided test function, or
-
findIndex()- Description: Returns the index of the first element in the array that satisfies the provided test function, or
-1if no element is found. - Example:
const numbers = [1, 2, 3, 4, 5]; const foundIndex = numbers.findIndex(num => num > 3); // Output: 3 (index of the element 4)
- Description: Returns the index of the first element in the array that satisfies the provided test function, or
-
flat()- Description: Creates a new array with all sub-array elements concatenated recursively up to the specified depth.
- Example:
const nestedArray = [1, [2, [3, [4]]]]; const flatArray = nestedArray.flat(Infinity); // Output: [1, 2, 3, 4]
-
flatMap()- Description: Maps each element using a mapping function, then flattens the result into a new array.
- Example:
const numbers = [1, 2, 3]; const mappedAndFlattened = numbers.flatMap(num => [num * 2, num * 3]); // Output: [2, 3, 4, 6, 6, 9]
-
forEach()- Description: Executes a provided function once for each array element.
- Example:
const fruits = ['apple', 'banana', 'orange']; fruits.forEach(fruit => console.log(fruit)); // Output: "apple", "banana", "orange"
-
includes()- Description: Determines whether an array includes a certain value, returning
trueorfalse. - Example:
const numbers = [1, 2, 3, 4, 5]; console.log(numbers.includes(3)); // Output: true console.log(numbers.includes(6)); // Output: false
- Description: Determines whether an array includes a certain value, returning
-
indexOf()- Description: Returns the first index at which a given element is found in the array, or
-1if not found. - Example:
const numbers = [1, 2, 3, 4, 5]; console.log(numbers.indexOf(3)); // Output: 2 console.log(numbers.indexOf(6)); // Output: -1
- Description: Returns the first index at which a given element is found in the array, or
-
join()- Description: Joins all elements of an array into a string using a specified separator.
- Example:
const fruits = ['apple', 'banana', 'orange']; const fruitString = fruits.join(', '); // Output: "apple, banana, orange"
-
keys()- Description: Returns a new Array Iterator object that contains the keys for each index in the array.
- Example:
const fruits = ['apple', 'banana', 'orange']; const iterator = fruits.keys(); for (const index of iterator) { console.log(index); } // Output: 0, 1, 2
-
lastIndexOf()- Description: Returns the last index at which a given element is found in the array, or
-1if not found. - Example:
const numbers = [1, 2, 3, 4, 2]; console.log(numbers.lastIndexOf(2)); // Output: 4 (last index of 2)
- Description: Returns the last index at which a given element is found in the array, or
-
map()- Description: Creates a new array with the results of calling a provided function on every element in the array.
- Example:
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); // Output: [2, 4, 6, 8, 10]
Certainly! Let's continue with the remaining array instance methods in JavaScript:
pop()
- Description: Removes the last element from an array and returns that element.
- Example:
const numbers = [1, 2, 3, 4, 5]; const removedElement = numbers.pop(); // Output: numbers = [1, 2, 3, 4], removedElement = 5
push()
- Description: Adds one or more elements to the end of an array and returns the new length of the array.
- Example:
const numbers = [1, 2, 3, 4]; const newLength = numbers.push(5, 6); // Output: numbers = [1, 2, 3, 4, 5, 6], newLength = 6
reduce()
- Description: Reduces an array to a single value by applying a provided function to each element, resulting in a single accumulated value.
- Example:
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // Output: sum = 15 (sum of all elements)
reduceRight()
- Description: Similar to
reduce(), but it processes the elements of the array from right to left. - Example:
const numbers = [1, 2, 3, 4, 5]; const concatenatedString = numbers.reduceRight((accumulator, currentValue) => accumulator + currentValue, ''); // Output: concatenatedString = "54321"
reverse()
- Description: Reverses the order of elements in an array in place.
- Example:
const numbers = [1, 2, 3, 4, 5]; numbers.reverse(); // Output: numbers = [5, 4, 3, 2, 1]
shift()
- Description: Removes the first element from an array and returns that element, shifting all subsequent elements one position to the left.
- Example:
const numbers = [1, 2, 3, 4, 5]; const removedElement = numbers.shift(); // Output: numbers = [2, 3, 4, 5], removedElement = 1
slice()
- Description: Returns a shallow copy of a portion of an array into a new array selected from start to end (end not included).
- Example:
const numbers = [1, 2, 3, 4, 5]; const subArray = numbers.slice(1, 3); // Output: subArray = [2, 3]
some()
- Description: Tests whether at least one element in the array passes the provided test function, returning
trueorfalse. - Example:
const numbers = [1, 2, 3, 4, 5]; const hasEvenNumber = numbers.some(num => num % 2 === 0); // Output: hasEvenNumber = true
sort()
- Description: Sorts the elements of an array in place and returns the sorted array.
- Example:
const fruits = ['banana', 'apple', 'orange']; fruits.sort(); // Output: fruits = ['apple', 'banana', 'orange']
splice()
- Description: Adds or removes elements from an array at a specified index, modifying the original array.
- Example:
const numbers = [1, 2, 3, 4, 5]; const removedElements = numbers.splice(2, 2, 6, 7); // .splice(startIndex, deleteCount, items to insert) // Output: numbers = [1, 2, 6, 7, 5], removedElements = [3, 4]
toLocaleString()
- Description: Returns a string representing the elements of an array, formatted as a localized string based on the given locale and options.
- Example:
const numbers = [1234.56, 7890.12]; const formattedNumbers = numbers.toLocaleString('en-US'); // Output: formattedNumbers = "1,234.56,7,890.12"
toString()
- Description: Returns a string representing the array and its elements, separated by commas.
- Example:
const fruits = ['apple', 'banana', 'orange']; const fruitsString = fruits.toString(); // Output: fruitsString = "apple,banana,orange"
unshift()
- Description: Adds one or more elements to the beginning of an array and returns the new length of the array.
- Example:
const numbers = [2, 3, 4]; const newLength = numbers.unshift(1); // Output: numbers = [1, 2, 3, 4], newLength = 4
Q/A
-
Question: Explain the difference between
forEach()andmap()methods.- Explanation: Both
forEach()andmap()are array iteration methods, but they have different purposes.forEach()is used to iterate over each element in an array and execute a provided callback function for each element. It doesn't return a new array. On the other hand,map()also iterates over each element and executes a callback function, but it returns a new array containing the results of the callback function for each element.
- Explanation: Both
-
Question: What is the purpose of the
filter()method?- Explanation: The
filter()method is used to create a new array containing elements that pass a provided test (specified by a callback function). It iterates through each element in the array and includes only those elements for which the callback function returnstrue.
- Explanation: The
-
Question: How can you remove elements from an array using the
splice()method?- Explanation: The
splice()method can be used to add or remove elements from an array at a specified index. To remove elements, you need to specify the index from which you want to remove elements and the number of elements to remove. For example,arr.splice(2, 3)removes three elements starting from the index2.
- Explanation: The
-
Question: Explain the use of the
reduce()method.- Explanation: The
reduce()method is used to reduce an array to a single value. It executes a provided callback function for each element of the array, resulting in a single accumulated value. The callback function takes two arguments: the accumulator and the current element. The initial value of the accumulator can be specified as the second argument ofreduce().
- Explanation: The
-
Question: How can you add elements to the end of an array using the
push()method?- Explanation: The
push()method is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array. For example,arr.push(6)adds the element6to the end of the arrayarr.
- Explanation: The
-
Question: Explain the purpose of the
every()method.- Explanation: The
every()method tests whether all elements in an array pass a provided test (specified by a callback function). It returnstrueif all elements pass the test; otherwise, it returnsfalse. The iteration stops if any element fails the test.
- Explanation: The
-
Question: How can you find the index of the first occurrence of an element in an array using the
indexOf()method?- Explanation: The
indexOf()method is used to find the index of the first occurrence of a specified element in an array. It returns the index if the element is found; otherwise, it returns-1.
- Explanation: The
-
Question: What is the purpose of the
slice()method?- Explanation: The
slice()method is used to create a shallow copy of a portion of an array into a new array. It takes two arguments: the start index (inclusive) and the end index (exclusive). If the end index is not provided, the method will copy until the end of the array.
- Explanation: The
-
Question: Explain the use of the
find()method.- Explanation: The
find()method is used to find the first element in an array that satisfies a provided test (specified by a callback function). It returns the first matching element, orundefinedif no element satisfies the condition.
- Explanation: The
-
Question: How can you check if an element is present in an array using the
includes()method?- Explanation: The
includes()method is used to check if an array includes a specific element. It returnstrueif the element is found; otherwise, it returnsfalse.
- Explanation: The
These questions cover a range of array methods and their applications in JavaScript, showcasing the different functionalities that can be achieved using these methods.