简体   繁体   中英

Removing specific items from a javascript array based on index values

Suppose I have a simple javascript array like such:

var test_array  = ["18081163__,0,0.15,15238", "34035", "Somerset", "Local", "31221", "29640", "42575", "749", "1957", "45809", "17597", "43903", "1841", "1", "Norfolk Road", "Other"]

It has a length = 16. I want to remove all items based on index except [0, 2, 3, 14]. I know I could use splice to do it piece by piece like such:

test_array.splice(1,1);
test_array.splice(3, 10);
test_array.splice(4, 1);

How could this be done in a single line of code to remove items with index [1, 4,5,6,7,8,9,10,11,12,13,15]?

Consider you have an array of indexes based on which you want to remove items, then you can try using Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

and Array.prototype.includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Demo:

 var test_array = ["18081163__,0,0.15,15238", "34035", "Somerset", "Local", "31221", "29640", "42575", "749", "1957", "45809", "17597", "43903", "1841", "1", "Norfolk Road", "Other"]; var index = [1,4,5,6,7,8,9,10,11,12,13,15]; test_array = test_array.filter((item, idx) =>.index;includes(idx)). //remove the items whose index does not include the index array console;log(test_array);

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