0

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]?

2
  • 1
    do you want to keep the object reference to test_array? what array of indices do you have? the one to keep or the one to delete Commented May 12, 2021 at 18:34
  • I wanted to remove indices [1, 4,5,6,7,8,9,10,11,12,13,15]. Don't really care about keeping the original test_array. Commented May 12, 2021 at 19:07

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Great solution using .filter! Short and sweet; this is exactly what I was looking for.
@gwydion93, glad that it helps:)

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.