Jordan Palmer
Jordan Palmer

Reputation: 11

Why is splice function giving me a singular output versus an array

This is my code

var arr = [1, 2, 3, 4];
var index = arr.indexOf(2);

arr = arr.splice(index, 1);
console.log(arr);

In theory it should index 2, so value of index should be 1. Then it should delete 1 item at that index and leave me with arr = [1,3,4] but it is giving me arr = [2].

Upvotes: 0

Views: 39

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10652

arr.splice doesn't return the spliced array instead it returns the removed/deleted elements as an array. It also doesn't create a new array, it modifies the actual array so you don't have to reassign.

You can just use:

var arr = [1, 2, 3, 4];
var index = arr.indexOf(2);
arr.splice(index, 1);
console.log(arr);

Upvotes: 1

Lab
Lab

Reputation: 226

arr.splice(index, 1); means to alter arr itself, and returns the value(s) that arr has been removed.

Hence arr=arr.splice(index,1) makes arr became the value arr removed at the right hand side.

Upvotes: 0

Related Questions