-1

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?

rrbest
  • 1,309
  • 3
  • 11
  • 20
  • You mean [Array.prototype.splice()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)? – Alon Eitan Jul 27 '17 at 04:15
  • Can't you just put an `if` statement and exclude the index you want? – ecain Jul 27 '17 at 04:16
  • 2
    Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Ebrahim Poursadeqi Jul 27 '17 at 04:19

2 Answers2

2

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.
Manish
  • 4,082
  • 3
  • 28
  • 39
  • I was misunderstanding what splice did. I thought it simply returned the item you referenced and not altered the original array. Now I know, thanks. – rrbest Jul 27 '17 at 04:42
0

var num = [5, 2, 9, 4, 3, 2, 3, 3, 5];
document.getElementById("demo").innerHTML = num;

function myFunction() {
 num.splice(5,1);
    document.getElementById("demo").innerHTML = num;
}
<!DOCTYPE html>
<html>
<body>

<p>Removes the fifth element</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

</body>
</html>
Eggineer
  • 204
  • 5
  • 15