Design & Download
Your JS Library
in Seconds!!!

Snippet: toggle() - Toggling Array Values

Written by Christopher West (cwest) on December 29, 2015.
If specific values are in an array they are removed but if they are not in the array they are added.
function toggle(array, valuesToToggle, opt_fnTestEquality) {
  array = slice(array);
  valuesToToggle = slice(valuesToToggle);
  for (var j, i = array.length, valuesCount = valuesToToggle.length; i--;) {
    for (j = valuesCount; j--;) {
      if (opt_fnTestEquality ? opt_fnTestEquality(array[i], valuesToToggle[j]) : (array[i] === valuesToToggle[j])) {
        array.splice(i, 1);
        valuesToToggle.splice(j, 1);
        valuesCount--;
      }
    }
  }
  return array.concat(valuesToToggle);
}

toggle(...) API Documentation

Toggles values in an array, adding the values that are missing from the array and removing those that are there.

Parameters

  1. array {Array}:
    The array whose values should be toggled. A copy of this array with the values toggled will be returned.
  2. valuesToToggle {Array}:
    The array of values to either add to (if they are present) or remove from (if they are missing) array.
  3. opt_fnTestEquality {Function}:
    Optional. If not given strict equality (===) will be used to compare values. If specified, this function will be used to determine if two values are equal. The first argument will be the value within array to be tested and the second will be the value within valuesToToggle to be tested.

Returns

A duplicate of array with the common values of valuesToToggle removed and the missing values added.