1

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

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

Charlie
  • 10,054
  • 17
  • 74
  • 133
volvereabhi
  • 120
  • 12
  • For more info you can check this [answer](https://stackoverflow.com/questions/3596089/how-to-remove-specific-value-from-array-using-jquery) – Peyu Jan 28 '20 at 18:32

3 Answers3

4

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.

Andy Mudrak
  • 767
  • 3
  • 6
jacob13smith
  • 917
  • 3
  • 12
  • 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. – Andy Mudrak Jan 28 '20 at 18:36
  • @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. – Roko C. Buljan Jan 28 '20 at 19:00
  • @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. – Andy Mudrak Jan 28 '20 at 19:24
  • @AndyMudrak yes, it depends. – Roko C. Buljan Jan 28 '20 at 19:27
2
arr.filter((name) => name !== temp);
Bloatlord
  • 320
  • 2
  • 8
2

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);
Gangadhar Gandi
  • 1,736
  • 7
  • 15