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

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 ]