Languages
[Edit]
EN

JavaScript - replace many elements in array

12 points
Created by:
Vanessa-Drake
718

In JavaScript, it is not intuitive to replace many elements in the 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

References

  1. Array.prototype.splice method - MDN Docs 

Alternative titles

  1. JavaScript - how to replace many elements in array?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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