DEV Community

Randy Rivera
Randy Rivera

Posted on

Add Items with splice()

  • Remember in the last challenge we mentioned that splice() can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
function numbers(arr) {
  arr.splice(3, 1, 13, 14);
  return arr;

console.log(numbers([10, 11, 12, 12, 15])); will display 
[ 10, 11, 12, 13, 14, 15 ]
Enter fullscreen mode Exit fullscreen mode
  • The second entry of 12 is removed, and we add 13 and 14 at the same index.
  • Here, we begin with an array of numbers. Then, we pass the following to splice(): The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note: There can be any number of elements (separated by commas) of which can get inserted following the number of elements to be deleted.

Top comments (0)