0

I have an array:

arr = ["a","b","c"];

How could I do in order to remove value "c" and then return array ["a","b"]?

2

3 Answers 3

2

You can find the index of the item being removed with Array.prototype.indexOf and you can eliminate the particular element with Array.prototype.splice, like this

var arr = ["a","b","c"];
arr.splice(arr.indexOf("c"), 1);
console.log(arr);
# [ 'a', 'b' ]

The second parameter passed to splice is to instruct how many elements to be removed from the index specified with the first parameter.

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

6 Comments

@Two-BitAlchemist But that removes only the last element. What if c is in the middle?
Then you use a different method. I mention pop because it is not clear from the question which is more suited to the OP's use case. If the element to be removed always happens to be last, no need to compute indexOf.
I've just tried your method. And it returned value "c" instead of array ["a","b"].
@user3247703 I think it was not clear earlier. Please check the update now.
It still turned out value "c". I already know "splice", which cut off element from array. But it normally returns removed value instead of array. And in this case, I need the inverse values of splice method.
|
0
return arr.filter(function(e) { return (e !== 'c') ; });

Comments

0

Just find in arr.splice(arr.indexOf("c"));

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.