0

var arr = [ "alice","bob","charli","dane","elisha","furnos"]; var temp = "bob";

I want to remove bob from arr by using variable temp.

1
  • For more info you can check this answer Commented Jan 28, 2020 at 18:32

3 Answers 3

3

This is an easy one liner:

arr.splice( arr.indexOf(temp), 1 );

Looks for the variable temp in the array and removes one element at that index.

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

4 Comments

I like this answer because it modifies the existing array, and does not return a new copy of the array with the element removed, as the other answers would do. If you do want a copy, however, then the other options are better. But I think the requestor did want it to modify the existing array, so I think this is best.
@AndyMudrak some type of clean programming implies we do keep original arrays unmodified. Memory is not an issue nowadays... Garbage collector is fast. Keep the original array? Precious. Also, indexOf stops as soon a match is found. Therefore is at times faster. Whereas filter will iterate the entire array no matter how many items you have. OK nowadays in V8 loops are extremely fast so we don't need to care much. But just saying.
@RokoC.Buljan, I agree with what you're saying here, and maybe the best answer would be to explain both options and why you would do one over the other. My assumption and preference was based on "removing" something from an array as per the way the question was worded as truly removing the element from the existing array. You could make an argument that if you modify the array, this takes effect on all references to this array everywhere else as well. That might be more precious than preserving the original array. It depends on the use case.
@AndyMudrak yes, it depends.
1

We can use Javascript array's filter method to remove the required item.

var arr = ["alice", "bob", "charli", "dane", "elisha", "furnos"];
var temp = "bob";
var filteredArray = arr.filter(item => item !== temp);
console.log(filteredArray);

OR

With Jquery we can go with grep,

var arr = ["alice", "bob", "charli", "dane", "elisha", "furnos"];
var temp = "bob";
arr = jQuery.grep(arr, function (value) {
    return value != temp;
});
console.log(arr);

Comments

1
arr.filter((name) => name !== temp);

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.