javascript - Remove only 1 item from JS Array even if duplicates exist -


thought share in case people needed couldn't find similar.

i wondering if possible remove item array if duplicates of item exist.

lets @ code:

var myarray = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'd', 'd', 'e'],     itemtoremove = 'a',     itemtoadd = 'f'; 

for example above, want remove itemtoremove array, but, not want remove of them, 1. want add itemtoadd.

to give little context, build category/personality based quiz, each answer question has category. want store chosen categories in array, display result dependent on category common @ end of quiz.

where question comes in user can go , change choice if want, if change mind, need remove previous category , add new one.

so answer simple.

var index = myarray.indexof(itemtoremove); if(index != -1) {     array.splice(index, 1); } 

as indexof function finds first index , finds 1 index can used remove 1 of array items.

we need careful indexof not supported ie8, ie8 pain in ass.

so following code can make indexof work you, must run before use function.

if (!array.prototype.indexof) {   array.prototype.indexof = function(elt /*, from*/)   {     var len = this.length >>> 0;      var = number(arguments[1]) || 0;     = (from < 0)          ? math.ceil(from)          : math.floor(from);     if (from < 0)       += len;      (; < len; from++)     {       if (from in &&           this[from] === elt)         return from;     }     return -1;   }; } 

sourced here: why doesn't indexof work on array ie8?

if has ideas of better way appreciated.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -