Max Lynn Max Lynn - 2 years ago 741
Javascript Question

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)) {
} else {
_.remove(scope.index, val);

Answer Source

The Set feature introduced by ES6 would do exactly that.

var s = new Set();

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

// Removing values

var array = Array.from(s);

Or if you want to keep using regular Arrays

function add(array, value) {
  if (array.indexOf(value) !== -1) {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download