-2

Suppose I have two arrays of objects

const array1 =  [{
        listName: 'My top 5 Sci-Fi Movies',
        listCreator: 'Anon',
        listItem: 'The Fifth Element'
      },
      {
        listName: 'My top 5 Sci-Fi Movies',
        listCreator: 'Anon',
        listItem: 'Cube'
      }]

and

const array2 = [{
        listName: 'My top 5 Sci-Fi Movies',
        listCreator: 'Anon',
        listItem: 'The Fifth Element'
      },
      {
        listName: 'My top 5 Sci-Fi Movies',
        listCreator: 'Dude',
        listItem: 'Cube'
      }]

I want to able to compare the two arrays and create a new array that only has unique members of array1, in this case

const uniqueArray = [{
            listName: 'My top 5 Sci-Fi Movies',
            listCreator: 'Anon',
            listItem: 'Cube'
          }]

I am using lodash library (but not necessary to solve this problem if not required) and I'd like to accomplish this in the fewest lines of code possible.

Kamal
  • 383
  • 1
  • 6
  • 16
  • 1
    Thanks for sharing your inputs and expected output. Can you share what you've tried? – stealththeninja Jul 25 '20 at 02:29
  • I had tried _.uniq, _.uniWith (used with _.isEqual) Set. I'm sorry I don't have details. I just learning JS and had been at this for a couple of days trying different things. – Kamal Jul 25 '20 at 21:39

2 Answers2

1

hello dear brother you use Hashset to fetch automatically Unique Data from list

HashSet<Integer>set = new HashSet<Integer>(list1);
List<Integer>list2 = new ArrayList<Integer>(set);

and then pass this Hashset to List again

ITS JAVA CODE BUT LOGIC IS SAME FOR EVERY LANGUAGE

Adnan Bashir
  • 645
  • 4
  • 8
0

After banging my head around the intertubes, I found a simple and elegant solution.

If I (using lodash) do

const arrNew = _.differenceWith(array1, array2, _.isEqual);

arrNew is a new array of unique items from array1. Hope this helps someone else out. Would love to see if there's another more performant solution.

https://lodash.com/docs/4.17.15#differenceWith

Kamal
  • 383
  • 1
  • 6
  • 16