How to use JavaScript Array splice()

Array splice

Array splice() method

Program to use JavaScript Array splice() method

let a = [1, 2, 3, 7, 5];
    let b = a.splice(3, 1, 4);
    
    console.log(a);
    console.log(b);
    

Output

[1, 2, 3, 4, 5]
    [7]
    

Steps Description

  • Declare two variable a and b
  • Initialize two variable with value of array a = [1, 2, 3, 7, 5] and b = a.splice(3, 1, 4)
  • Array splice() method adds or removes an array element and returns the removed element.
  • The value of b variable is displayed with the help of console.log inbuilt function

Array splice() method

Program to use JavaScript Array splice() method

let c = [2, 44, 32, 8, 10, 12, 14, 16, 18, 20];
    let d = c.splice(1, 2, 4, 6)
    
    console.log(c);
    console.log(d);
    

Output

[
      2,  4,  6,  8, 10,
     12, 14, 16, 18, 20
    ]
    [ 44, 32 ]
    

Steps Description

  • Declare two variable c and d
  • Initialize two variable with value of array c = [2, 44, 32, 8, 10, 12, 14, 16, 18, 20] and d = c.splice(1, 2, 4, 6)
  • Array splice() method adds or removes an array element and returns the removed element.
  • The value of d variable is displayed with the help of console.log inbuilt function

Array splice() method

Program to use JavaScript Array splice() method

let e = ['Cat', 'Dog', 'Tiger', 'Lion'];
    let f = e.splice(2, 0, 'Elephant', 'Bear');
    
    console.log(e);
    console.log(f);
    

Output

[ 'Cat', 'Dog', 'Elephant', 'Bear', 'Tiger', 'Lion' ]
    

Steps Description

  • Declare two variable e and f
  • Initialize two variable with value of array e = [‘Cat’, ‘Dog’, ‘Tiger’, ‘Lion’] and f = e.splice(2, 0, ‘Elephant’, ‘Bear’)
  • Array splice() method adds or removes an array element and returns the removed element.
  • The value of f variable is displayed with the help of console.log inbuilt function