21

I want to have a simple array of values, ie

var simpleArray = ["SE1","SE2","SE3"];

I want to check this array when an action happens (a click on a google map layer), that will pass a value to this function and either add the value to the array, or remove it from the array if it already exists.

I am now just a bit confused having seen .splice/push/inArray/indexOf (that doesn't work in IE)/grep (jQuery) - not sure what the best practice is.

1
  • You could take a look at underscorejs.org Commented Sep 12, 2013 at 13:19

4 Answers 4

36

Assuming the order of the items doesn't matter you can do something like this:

function toggleArrayItem(a, v) {
    var i = a.indexOf(v);
    if (i === -1)
        a.push(v);
    else
        a.splice(i,1);
}

The .indexOf() method does work in IE from version 9 onwards, but if you need to support older IE versions you can use a shim as explained at MDN. Or if you're using jQuery anyway use $.inArray() instead.

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

Comments

7

my ES* variant

const toggleArrayValue = (arrayList, arrayValue) =>
  arrayList.includes(arrayValue)
    ? arrayList.filter(el => el !== arrayValue)
    : [...arrayList, arrayValue]

Comments

6

extremely compact lodash version, using xor function, which is used to create a new array of values found only in one array and not the other

xor(array, [valueYouWantToToggle])

Comments

1

Also if the value is an object:

const eq = (a, b) => a == b

const toggle = (arr, item) => {
  const resultArray = [];
  let duplicate = false;
  for(let i = 0; i < arr.length; i++) {
    if(!eq(arr[i], item)) {
      resultArray.push(arr[i]);
    } else {
      duplicate = true
    }
  }
  if(!duplicate) {
    resultArray.push(item)
  }
  return resultArray;
}

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.