1

Thought I would share this in case people needed it as I couldn't find something similar.

I am wondering if it is possible to remove an item from an array even if duplicates of that item exist.

Lets look at some code:

var myArray = ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'd', 'd', 'e'],
    itemToRemove = 'a',
    itemToAdd = 'f';

For the example above, I want to remove itemToRemove from the array, BUT, I do not want to remove all of them, just 1. I then want to add itemToAdd.

To give a little context, I am build a category/personality based quiz, each answer to a question has a category. I want to store all chosen categories in an array, then display a result dependent on which category is most common at the end of the quiz.

Where the question comes in is the User can go back and change their choice if they want, so if they do change their mind, I need to remove the previous category and add the new one.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
lukehillonline
  • 2,430
  • 2
  • 32
  • 48
  • Wouldn't your life be alot easier when you would use a JSON object for this and using some kind of primary key?````{1:'a', 2:'a', 3:'b'}````? – com2ghz Jan 27 '16 at 13:09
  • I did think about this, but I thought it would be easier not to know/worry about keys. If I was to go down that route, I would need my back end dev to spit out a list of categories which I then need to turn into an Object which I can then add a count to each Object Key. The count being the amount of time the category is selected in the quiz. So I actually think its easier for the code not to worry about that, just chuck them all in an array and get the total at the end. I do agree though that an Object would be cleaner and easier to read. – lukehillonline Jan 27 '16 at 13:19

1 Answers1

2

So this answer to this is actually very simple.

var index = myArray.indexOf(itemToRemove);
if(index != -1) {
    array.splice(index, 1);
}

As the indexOf function only finds the first index and only finds 1 index this can be used to remove just 1 of the array items.

We also need to be careful with indexOf as it is not supported with IE8, as always IE8 is a pain in the ass.

So the following code can make indexOf work for you, it must be run before you use the function.

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

Sourced from here: Why doesn't indexOf work on an array IE8?

If anyone has any ideas of a better way to do this they would be much appreciated.

Community
  • 1
  • 1
lukehillonline
  • 2,430
  • 2
  • 32
  • 48