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

Max Lynn picture Max Lynn · May 6, 2016 · Viewed 87.6k times · Source

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);
}

Answer

Afzal Hossain picture Afzal Hossain · Jan 11, 2017

You can use _.union

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