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?

5
  • 1
    are you looking for array.splice? Commented Apr 15, 2015 at 16:58
  • @InvernoMuto I am not sure whether I can use array.splice in this situation. Commented Apr 15, 2015 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 Commented Apr 15, 2015 at 17:01
  • you can definitely use str.indexOf(searchValue[, fromIndex]) where fromIndex is the starting recurrence of your value Commented Apr 15, 2015 at 17:03
  • So many answers, not of which does what asked for. See my answer, it does exactly what you asked for Commented Apr 15, 2015 at 17:11

4 Answers 4

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

this will remove first element not the last
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>

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.