How to useapply() Method in Javascript
The apply() method is an older approach to copying an array, but it is less commonly used compared to the spread operator and slice() method. The apply() method calls a function with a given value and an array of arguments. To copy an array using apply(), you can use the concat() method along with apply() to concatenate the elements of the original array into a new array.
Syntax:
const copiedArray = Array.apply(null, originalArray);
Example: In this example, we will see the use of apply() Method.
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = Array.apply(null, originalArray);
// Output: [1, 2, 3, 4, 5]
console.log(copiedArray);
Output
[ 1, 2, 3, 4, 5 ]
Copy Array Items into Another Array in JavaScript
We will see how to copy array items into another array in JavaScript. This operation is valuable when you need to generate a new array containing either identical or a subset of elements from an original array.
These are the following ways to solve this problem:
Table of Content
- Using the Spread Operator (…)
- Using slice() Method
- Using apply() Method
- Using Array.concat() Method
- Using push() Method
- Using map() Method
Contact Us