Languages
[Edit]
EN

JavaScript - how to replace many elements in array?

12 points
Created by:
Vanessa-Drake
448

In JavaScript it is not intuitive at first time how to replace many elements in array. Replace operation can be achieved with Array.prototype.splice method. This article is focused on how to do it.

1. Replace many elements with Array.prototype.splice method example

//  index:    0    1    2    3    4    5    6
var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

// removing 4 elements sice 1st index position 
// inserting sice 1st index position 4 elements
array.splice(1, 4, 'new item 1', 'new item 2', 'new item 3', 'new item N');

console.log(array);

Output:

[
  'a',
  'new item 1',
  'new item 2',
  'new item 3',
  'new item N',
  'f',
  'g'
]

Notes about Array.prototype.splice method:

  • takes as first argument index of begining of removed elements
  • takes as second argument number of removed elements
  • takes as third and next arguments added elements

Refrences

  1. Array.prototype.splice method - MDN Docs 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join