Page Content

Tutorials

JavaScript Arrays Methods for Adding and Removing Values

JavaScript Arrays Methods

JavaScript Array Methods are functions that are linked to array objects and can be used to manipulate them in different ways. Methods do actions rather than storing a value like properties do. These are built-in JavaScript functions that let you work with arrays. Usually, dot notation is used to access them (arrayName.methodName()). Since array methods reside on Array.prototype, all array instances can access them.

Push, pop, shift, and unshift are explained here:

  • push() Adds elements to an array’s end. Push() adds parameters to the array in sequence. After adding elements, push() returns the array length.
  • Push() is the typical way for adding a single element, however fruits[fruits.length] = is similar.
  • pop() The last element of an array is removed by this function. It restores the removed piece. Pop() reduces array length by 1.
  • unshift() This method starts an array with one or more elements. Passing arguments adds numerous pieces like push(). The array length is returned after adding elements. For space at the start, components are moved to higher indices.
  • The shift() method removes the first element from an array. It restores the removed piece. To make up for the missing element, all subsequent elements are pushed down one index.

To manipulate arrays as data structures like stacks (using push() to add and pop() to remove, operating on the end) or queues (using push() to add to the end and shift() to remove from the beginning, or unshift() to add to the beginning and shift() to remove from the beginning), these four methods are essential. Adding or deleting from the start requires re-indexing all following elements, hence push() and pop() are usually more efficient than shift() and unshift().

Sort, slice, and splice manipulate array contents.

  • The sort() function Reordering array elements is done with sort(). As strings, it organises elements alphabetically by default. “10” comes before “2” alphabetically, therefore it sorts as [example in previous turn]. Arguments must include a comparison function to sort numbers or other data. The function should return a negative value if a should come before b, a positive value if a should come after b, and zero if their order doesn’t matter.
  • Slice() extraction Slice() returns a piece of an array as a new array. This does not change the array. 2 optional arguments: startIndex (inclusive) and endIndex (exclusive). Leaving endIndex blank duplicates the array to the end. It shallow copies the array if both parameters are missing. Negative parameters designate array end positions.
  • Splice() modifies Splice() is a strong, general-purpose array insert, remove, and replace technique. Most importantly, splice() alters the array in place, unlike slice(). Starting index, deleteCount, and any number of optional item parameters are required. An array of deleted entries is returned.

Though similar, splice() and slice() execute quite different tasks.

Adding and Removing Elements Using Array Methods

For efficient array addition and removal, JavaScript has various built-in methods. These methods operate on an array object.

Adding Elements:

Arrays can be expanded in numerous ways. Most recommended ways add elements to the array’s end or beginning.

push() adds new elements to the end of an array. It alters the array. After adding elements, push() returns the array length.

unshift(): Adds elements to the start of an array. Similar to push(), it updates the array and returns its length. Unshift() requires renumbering all elements to shift them to higher indices, which can be slower than adding to the end for large arrays.

Adding with Index Assignment: Use square brackets to assign values to specified indexes for addition or replacement. Replace the value at the index if it exists. If the index is longer than the array’s length, the length property is modified and all indices between the old and new ends are produced with “empty items” or undefined values. This is a bad approach to add values since it can cause overwriting or sparse arrays with empty slots.

Element Removal:

Similar to adding, most removal methods target array ends.

  • pop() removes an array’s last element. Modifies the array and returns the removed element’s value. This approach reduces array length by 1. Push and pop are used to treat an array like a stack (Last-In, First-Out).
  • Shift(): Removes the first entry from an array. Modifies the array and returns the removed element’s value. shift() decreases array length by 1 and shifts subsequent elements to a lower index. Functions like shift() and unshift() consider an array as a queue. Like unshift(), shifting elements affects performance.
  • The delete operator: The delete operator with an array index removes the element’s value but not the element itself. That index remains undefined or “hole” and the array’s length doesn’t change. This behaviour leaves gaps and doesn’t shorten arrays, which is undesirable.

Splice() General-Purpose Modification:

Insert, delete, or replace elements anywhere in an array with the splice() method. In place, it changes the array’s length and shifts elements.

Splice() takes numerous arguments: startIndex, deleteCount, item1, item2,…

  • startIndex is the index to change the array.
  • deleteCount: Number of entries to remove from startIndex. Remove no elements if 0.
  • item1, item2,: Add optional elements (item1, item2,) to the array starting at startIndex. Additions restore deleted components or insert them if deleteCount is 0.

let myList = [“Milk”, “Bread”, “Apples”];
// Replace 1 element at index 1 (“Bread”) with “Bananas” and “Eggs”
myList.splice(1, 1, “Bananas”, “Eggs”);
console.log(myList);
// Output: [“Milk”, “Bananas”, “Eggs”, “Apples”]
// Remove 2 elements starting from index 0 (“Milk”, “Bananas”)
myList.splice(0, 2);
console.log(myList);
// Output: [“Eggs”, “Apples”]
// Insert 2 elements (“Carrots”, “Lettuce”) starting at index 1 without removing any
myList.splice(1, 0, “Carrots”, “Lettuce”);
console.log(myList);
// Output: [“Eggs”, “Carrots”, “Lettuce”, “Apples”]

Removing Elements by setting length

Setting the length attribute to a lesser value removes elements from the end of an array.

let myArray = [1, 10, 48, 53, 54];
myArray.length = 3; // Truncates the array to the first 3 elements
console.log(myArray);
// Output: [1, 53, 54]

In conclusion, JavaScript’s push(), unshift(), pop(), shift(), and splice() methods efficiently manage dynamic array components. You can add or remove elements from either end or elsewhere in the array with these methods. Direct index assignment adds elements, although it’s less predictable than particular procedures. The remove operator leaves gaps and doesn’t update length when removing array elements.

Index