Mutate array by copy
When working with arrays in JavaScript, it’s essential to understand the distinction between mutating an array in place and creating a new array by copying its elements. Let’s explore both approaches:
Mutating the Original Array (In-Place)
- When you want to modify the original array directly, you can use methods that mutate the array without creating a new one.
- Examples of such methods include:
Array#push()
: Adds elements to the end of the array.Array#pop()
: Removes the last element from the array.Array#splice()
: Adds or removes elements at a specific position.Array#sort()
: Sorts the array in place.Array#reverse()
: Reverses the order of elements.
- These methods alter the original array, so use them carefully.
Creating a New Array by Copying Elements
- Sometimes you need to create a new array based on the existing one without modifying the original.
- Common methods for creating a new array include:
Array#map()
: Creates a new array by applying a function to each element.Array#filter()
: Creates a new array with elements that pass a test.Array#slice()
: Creates a shallow copy of a portion of the array.Array.from()
: Converts an iterable (like an array-like object) into an array.- Spread syntax (
[...originalArray]
): Creates a shallow copy of the entire array.
- These methods do not mutate the original array.
Example: Mutating an Array Using
map()
- Suppose we have an array of numbers, and we want to double each number in place:JavaScript
let numbers = [1, 2, 3]; numbers = numbers.map((x) => x * 2); console.log(numbers); // [2, 4, 6]
- Note that we reassign the result of
map()
back to thenumbers
variable.
- Suppose we have an array of numbers, and we want to double each number in place:
Example: Creating a New Array by Copying Elements
- If we want to create a new array with the doubled numbers without modifying the original:JavaScript
const originalNumbers = [1, 2, 3]; const doubledNumbers = originalNumbers.map((x) => x * 2); console.log(doubledNumbers); // [2, 4, 6] console.log(originalNumbers); // [1, 2, 3] (unchanged)
- If we want to create a new array with the doubled numbers without modifying the original:
Remember to choose the appropriate method based on whether you want to mutate the original array or create a new one! ππ’π 1: Stack Overflow - How to mutate original array in JavaScript .map() function? 2: Medium - Understanding mutating vs. non-Mutating methods in JavaScript array 3: freeCodeCamp.org - How to clone an array in JavaScript 4: DigitalOcean - How To Use Array Methods in JavaScript: Mutator Methods 5: SitePoint - A Guide to Variable Assignment and Mutation in JavaScript
Comments
Post a Comment