Add only unique objects to an array in JavaScript Add only unique objects to an array in JavaScript arrays arrays

Add only unique objects to an array in JavaScript


The Underscore findWhere function does exactly what you need - it's not an indexOf search by object identity, but searches objects whose properties have the same values as the input.

if (_.findWhere(shippingAddresses, toBeInserted) == null) {    shippingAddresses.push(toBeInserted);}


Basic example using lodash union method:

var a = [1,2,3];// try to add "1" and "4" to the above Arraya = _.union(a, [1, 4]);console.log(a);
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>