Insert Value at Array Index

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of inserting values into an array at a specified index using JavaScript. You will learn how to use the Array.prototype.splice() method to insert values after a given index with a delete count of 0. This lab will provide you with hands-on experience in manipulating arrays in JavaScript and help you understand how to mutate the original array while inserting new values.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28401{{"`Insert Value at Array Index`"}} javascript/data_types -.-> lab-28401{{"`Insert Value at Array Index`"}} javascript/arith_ops -.-> lab-28401{{"`Insert Value at Array Index`"}} javascript/comp_ops -.-> lab-28401{{"`Insert Value at Array Index`"}} javascript/spread_rest -.-> lab-28401{{"`Insert Value at Array Index`"}} end

How to Insert a Value at a Specific Index in an Array using JavaScript

To insert a value at a specific index in an array using JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Array.prototype.splice() method with an appropriate index and a delete count of 0, spreading the given values to be inserted.
  3. The insertAt function takes an array, an index, and one or more values to be inserted after the specified index.
  4. The function mutates the original array and returns the modified array.

Here's an example of the insertAt function in action:

const insertAt = (arr, i, ...v) => {
  arr.splice(i + 1, 0, ...v);
  return arr;
};

let myArray = [1, 2, 3, 4];
insertAt(myArray, 2, 5); // myArray = [1, 2, 3, 5, 4]

let otherArray = [2, 10];
insertAt(otherArray, 0, 4, 6, 8); // otherArray = [2, 4, 6, 8, 10]

In the example above, the insertAt function is used to insert the value 5 after the second index of the myArray array, and to insert the values 4, 6, and 8 after the first index of the otherArray array.

Summary

Congratulations! You have completed the Insert Value at Array Index lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like