Using lodash push to an array only if value doesn't exist?

I'm trying to make an array that if a value doesn't exist then it is added but however if the value is there I would like to remove that value from the array as well.

Feels like Lodash should be able to do something like this.

I'm interested in your best practises suggestions.

Also it is worth pointing out that I am using Angular.js

* Update *

if (!_.includes(scope.index, val)) {
    scope.index.push(val);
} else {
  _.remove(scope.index, val);
}

You can use _.union

_.union(scope.index, [val]);

The Set feature introduced by ES6 would do exactly that.

var s = new Set();

// Adding alues
s.add('hello');
s.add('world');
s.add('hello'); // already exists

// Removing values
s.delete('world');

var array = Array.from(s);

Or if you want to keep using regular Arrays

function add(array, value) {
  if (array.indexOf(value) === -1) {
    array.push(value);
  }
}

function remove(array, value) {
  var index = array.indexOf(value);
  if (index !== -1) {
    array.splice(index, 1);
  }
}

Using vanilla JS over Lodash is a good practice. It removes a dependency, forces you to understand your code, and often is more performant.


Perhaps _.pull() can help:

var _ = require('lodash');

function knock(arr,val){ 
   if(arr.length === _.pull(arr,val).length){
      arr.push(val);
   } 
   return arr;
}

Mutates the existing array, removes duplicates as well:

> var arr = [1,2,3,4,4,5];

> knock(arr,4);
[ 1, 2, 3, 5 ]

> knock(arr,6);
[ 1, 2, 3, 5, 6 ]

> knock(arr,6);
[ 1, 2, 3, 5 ]

Use includes function to check that item is exists in array, and remove to delete existing item.

function addOrRemove(arr, val) {
  if (!_.includes(arr, val)) {
    arr.push(val);
  } else {
    _.remove(arr, item => item === val);
  }
  console.log(arr);
}

var arr = [1, 2, 3];
addOrRemove(arr, 1); // arr = [2, 3]
addOrRemove(arr, 4); // arr = [2, 3, 4]
addOrRemove(arr, 2); // arr = [3, 4]
<script src="https://raw.githubusercontent.com/lodash/lodash/4.11.2/dist/lodash.min.js"></script>

In this case you can use 'concat' to push and 'uniq' to validate unique values:

example:

var ar = [1, 2, 3, 1, 5, 2, 4]
ar = _.uniq(_.concat(ar, 9))
//[1, 2, 3, 5, 4, 9]

e.g.: https://codepen.io/dieterich/pen/xeZNJY

ref.: https://lodash.com/docs/4.17.11#uniq