1

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
  • 818
  • 1
  • 14
  • 34
  • 1
    are you looking for array.splice? – ale Apr 15 '15 at 16:58
  • @InvernoMuto I am not sure whether I can use array.splice in this situation. – Pradip Shenolkar Apr 15 '15 at 16:59
  • You are Right, before to call splice you have to locate your "China" recurrence, you can use IndexOf otherwise LastIndexOf otherwise you havee to craft a custom IndexFilter – ale Apr 15 '15 at 17:01
  • you can definitely use str.indexOf(searchValue[, fromIndex]) where fromIndex is the starting recurrence of your value – ale Apr 15 '15 at 17:03
  • So many answers, not of which does what asked for. See my answer, it does exactly what you asked for – Sam Battat Apr 15 '15 at 17:11

4 Answers4

4

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
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
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>
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Ashesh
  • 3,499
  • 1
  • 27
  • 44
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,725
  • 1
  • 20
  • 29