How do I manipulate arrays

In JavaScript, arrays can be manipulated using various methods and properties. Here are some common ways to manipulate arrays:

  • push() - Adds one or more elements to the end of an array.
  • pop() - Removes the last element from an array and returns that element.
  • shift() - Removes the first element from an array and returns that element.
  • unshift() - Adds one or more elements to the beginning of an array.
  • splice() - Adds or removes elements from an array at a specified index.
  • slice() - Returns a shallow copy of a portion of an array into a new array object.
  • map() - Creates a new array populated with the results of calling a provided function on every element in the calling array.
  • filter() - Creates a new array with all elements that pass the test implemented by the provided function.
  • reduce() - Executes a reducer function on each element of the array, resulting in a single output value.

Here's an example of how to use some of these methods to manipulate arrays:

// Create an array let fruits = ["apple", "banana", "cherry"]; // Add an element to the end fruits.push("date"); // ["apple", "banana", "cherry", "date"] // Remove the last element let lastFruit = fruits.pop(); // returns "date" // Add an element to the beginning fruits.unshift("orange"); // ["orange", "apple", "banana", "cherry"] // Remove the first element let firstFruit = fruits.shift(); // returns "orange" // Splicing the array fruits.splice(1, 1, "grape"); // ["apple", "grape", "cherry"] // Using map let lengths = fruits.map(fruit => fruit.length); // [5, 5, 6]

JavaScript Arrays Array Manipulation push pop shift unshift splice slice map filter reduce