Search code examples
javascriptlodash

Append items of array or exclude if already exists


as I describe my problem in title, I need implement following algorithm:

I got some array of elements, e.g.:

let arr1 = [
  {id:1, foo1: '...', foo2: '...'}, 
  {id:2, foo1: '...', foo2: '...'}, 
  {id:3, foo1: '...', foo2: '...'}, 
];

in somewhere in my application I got another array arr2 which can contains elements which already are in arr1.

let arr2 = [
  {id:1, foo1: '...', foo2: '...'}, 
  {id:4, foo1: '...', foo2: '...'}, 
  {id:5, foo1: '...', foo2: '...'}, 
];

In case arr1 contains each element of arr2 I need exclude these elements from arr1. And in second case where arr2 contains least one element which is also not in arr1, all elements of arr2 will append to arr1.

I tried lodash's function _.xorBy(arr1, arr2, 'id') which doesn't work in all cases. I looked for in lodash's docs some another function for my needs but I didn't found anything.

Here is my expected behavior (I use just number but in real app there objects with this ids):

  • given: arr1=[1,2,3,4,5] and arr2=[1,2,3] => resultArr=[4,5]
  • given: arr1=[1,2,3,4,5] and arr2=[1,2,6] => resultArr=[1,2,3,4,5,6] //6 is different so append all

Can you help me solve my problem, or show my some elegant way to do that? Thanks in advice.


Solution

  • If the _.difference() array length between arr2 and arr1 is greater than 0, return a _.union() of the arrays. If not return the _.difference() between arr1 and arr2.

    Note 1: _.difference(arr2, arr1) is not equal to _.difference(arr1, arr2) because the order and references of result values are determined by the first array.

    Note 2: The example uses arrays of primitives. For arrays of objects use the By versions - _.differenceBy() and _.unionBy() with the property iteratee shorthand - _.differenceBy(arr1, arr2, 'id').

    const incEx = (arr1, arr2) => 
      _.difference(arr2, arr1).length > 0 ? 
        _.union(arr1, arr2) 
        : 
        _.difference(arr1, arr2);
    
    console.log(incEx([1,2,3,4,5], [1,2,3]));
    console.log(incEx([1,2,3,4,5], [1,2,6]));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>