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:

  1. 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.
  2. 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.
  3. 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 the numbers variable.
  4. 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)
      

Remember to choose the appropriate method based on whether you want to mutate the original array or create a new one! πŸš€πŸ”’πŸ”„ 1Stack Overflow - How to mutate original array in JavaScript .map() function? 2Medium - Understanding mutating vs. non-Mutating methods in JavaScript array 3freeCodeCamp.org - How to clone an array in JavaScript 4DigitalOcean - How To Use Array Methods in JavaScript: Mutator Methods 5SitePoint - A Guide to Variable Assignment and Mutation in JavaScript

Comments

Popular posts from this blog

New Tech Bloggie

FinTech App

JavaScript - Object.groupBy()