rrbest rrbest - 1 year ago 103
Javascript Question

How to exclude the nth item in an array in javascript?

I am aware of splice for returning the nth item in an array, but I have had trouble finding a method to do the exact opposite: exclude the nth item from an array.

For example I have an array [5, 2, 9, 4, 3, 2, 3, 3, 5], if i want to exclude the fifth item I would return an array [5, 2, 9, 4, 2, 3, 3, 5]. What is the most efficient way to do this?

Answer Source

I am aware of splice for returning the nth item in an array, but I have had trouble finding a method to do the exact opposite: exclude the nth item from an array.

What do you actually mean to say by that. Splice returns the nth element after excluding it from the array. It will return the element but will also remove it from the array. And the array will now not contain that element.

Below is the demo:

var arr=[5, 2, 9, 4, 3, 2, 3, 3, 5];
//will log the fifth element as splice removes the element amd returns it 
console.log("Removed :"+arr.splice(4,1));//5th element index is 4 2nd argumentn is the no of elements to remove
console.log("Altered Array:"+arr);// will log the latered array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download