0

I have a javascript array

var countries = ["India","USA","China","Canada","China"];

I want to remove "China" only from 2nd position, and return

var countries = ["India","USA","Canada","China"];

Something similar to java linkedlist.remove(index)

I have read following question but I don't know how to use it if there are duplicate elements in array. How do I remove a particular element from an array in JavaScript?

Community
  • 1
  • 1
Pradip Shenolkar
  • 779
  • 1
  • 10
  • 29

4 Answers4

2

Try splice():

countries.splice(2,1);

Here, first argument is the position and second is the number of elements to remove.

To get the index use indexOf(), -1 if not found:

countries.indexOf("China");

So you have:

var i = countries.indexOf("China");
if(-1 !== i) {
    countries.splice(i, 1);
}
1

You can use a mix of array.indexOf and array.splice.

var countries = ["India","USA","China","Canada","China"];
var first_china = countries.indexOf("China");

if(first_china > -1){
    countries.splice(first_china , 1);
}

The question you linked also has the same answer (https://stackoverflow.com/a/5767357). indexOf will return you the index of the first match it finds. So if there are duplicates, it will still only remove the first one.

Community
  • 1
  • 1
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
0

You can use the JavaScript Array splice() Method.

var countries = ["India", "USA", "China", "Canada", "China"];
document.getElementById("demo").innerHTML = countries;

function myFunction() {
  countries.splice(2, 1);
  document.getElementById("demo").innerHTML = countries;
}
<button onclick="myFunction()">SPLICE!</button>
<p id="demo"></p>
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
Ashesh
  • 3,230
  • 1
  • 20
  • 42
0
var c = ["India","USA","China","Canada","China"];
// provide the index you want to remove here (2)
var c2 = c.filter(function(item, idx) {if(idx != 2) return item;});

console.log(c2);

DEMO: http://jsfiddle.net/kf8epwnh/

Sam Battat
  • 5,647
  • 1
  • 18
  • 28