Given an Array with some elements, the task is to append an item to an array in JavaScript. This article contains several methods to append an item to an array in JavaScript. We will explain each approaches in detail with code examples.
Append an Item to the Beginning of an Array
The Array.unshift() method is used to add an item to the beginning of an array. First, we declare and initialize an array Arr
, and a variable newItem, then use the Array.unshift() method to append the item to the beginning of the array.
const Arr = [10, 20, 30, 40, 50]; const newItem = 5; Arr.unshift(newItem); // Output: [5, 10, 20, 30, 40, 50] console.log(Arr);
Append an Item to the End of an Array
The Array.push() method is used to add an item to the end of an array. First, we declare and initialize an array Arr, and a variable newItem. Then use the Array.push() method to append the item to the end of the array.
const Arr = [ 10, 20, 30, 40, 50 ]; const newItem = 60; Arr.push(newItem); // Output: [ 10, 20, 30, 40, 50, 60 ] console.log(Arr);
Append an Item to the Middle of an Array
The Array.splice() method is used to add an item to the middle of an array. First, we declare and initialize an array Arr, and a variable newItem. Then use the Array.splice() method to append the item to the middle of the array.
const Arr = [10, 20, 30, 40, 50]; const newItem = 25; const middleIndex = Math.floor(Arr.length / 2); Arr.splice(middleIndex, 0, newItem); // Output: [10, 20, 25, 30, 40, 50] console.log(Arr);
Append an Item at Specified Position of an Array
The Array.splice() method is used to add an item at a specified position in an array. First, we declare and initialize an array Arr, and a variable newItem. Then use the Array.splice() method to append the item at the specified position.
const Arr = [10, 20, 30, 40, 50]; const newItem = 15; const specifiedPosition = 1; Arr.splice(specifiedPosition, 0, newItem); // Output: [10, 15, 20, 30, 40, 50] console.log(Arr);
Append an Item After a Given Element in an Array
To append an item after a given element in an array, we can find the index of the given element. Then use the Array.splice() method to insert the new item at the position after the given element.
const Arr = [10, 20, 30, 40, 50]; const newItem = 25; const afterElement = 20; const index = Arr.indexOf(afterElement); if (index !== -1) { Arr.splice(index + 1, 0, newItem); } // Output: [10, 20, 25, 30, 40, 50] console.log(Arr);
Append an Item Before a Given Element in an Array
To append an item before a given element in an array, we can find the index of the given element. Then use the Array.splice() method to insert the new item at the position before the given element.
const Arr = [10, 20, 30, 40, 50]; const newItem = 15; const beforeElement = 20; const index = Arr.indexOf(beforeElement); if (index !== -1) { Arr.splice(index, 0, newItem); } // Output: [10, 15, 20, 30, 40, 50] console.log(Arr);