简体   繁体   中英

Remove elements from javascript array by position

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?

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.

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);
}

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> 

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM