Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

JavaScript - how to replace many elements in array?

0 contributions
12 points

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 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more