underscoreJS-сформировать новый массив с элементами в array1, но не в array2

Предположим, у меня есть array1 и array2 , нужно найти метод, с помощью которого я могу найти элементы в array1, но не в array2,

array1":[{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},{"name":"will","lastname":"rogers","emailId":"willrogers@gmail.com","$$key":"object:24"},{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}]
array2":[{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}]
**i need to get a new array** 
**result:**[{"name":"will","lastname":"rogers","emailId":"willrogers@gmail.com","$$key":"object:24"}]

1 ответ

  1. Вы можете использовать reject и некоторые:

    var result = _.reject(data.array1, item => _.some(data.array2, { $$key : item.$$key}));
    

    или без функции стрелки:

    var result = _.reject(data.array1, function(item) {
        return _.some(data.array2, { $$key : item.$$key}); 
    });
    

    var data = {
    	"array1":[
    		{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},
    		{"name":"will","lastname":"rogers","emailId":"willrogers@gmail.com","$$key":"object:24"},
    		{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}],
    
    	"array2":[
    		{"name":"tom","lastname":"jacob","emailId":"tomjacob@gmail.com","$$key":"object:4"},
    		{"name":"matt","lastname":"jacob","emailId":"mattjacob@gmail.com","$$key":"object:84"}]
    }
    
    var result = _.reject(data.array1, item => _.some(data.array2, { $$key : item.$$key}));
    
    document.getElementById('result').textContent = JSON.stringify(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>
    
    <p>
      <pre id="result"></pre>
    </p>