-1

For example I have this array:

0: {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: ""}
1: {myfield: "1f974a20-aa59-11e8-9666-ab3419ed3bc9", order: 0, value: ""}
2: {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: "One"}
3: {myfield: "af7401a0-aa6e-11e8-9653-ab3419ed3bc9", order: 1, value: "Two"}

I wanna be able to loop through it and pop/remove older version of duplicated array, in this example I wanted to keep Object 2 and pop/remove Object 0 since they both have exact same myfield

Would it be possible to do this using lodash?

Amy Lee
  • 277
  • 3
  • 15

2 Answers2

4

You can use _.uniqBy()

let arr = [ {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: ""}, {myfield: "1f974a20-aa59-11e8-9666-ab3419ed3bc9", order: 0, value: ""}, {myfield: "1f974a20-aa59-11e8-9653-ab3419ed3bc9", order: 0, value: "One"}, {myfield: "af7401a0-aa6e-11e8-9653-ab3419ed3bc9", order: 1, value: "Two"}];

let result = _.uniqBy(arr, 'myfield');
amrender singh
  • 7,949
  • 3
  • 22
  • 28
3

Try deep equating the array of objects using the isEqual and uniqWith methods.

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);

Here is the link to the documentation: https://lodash.com/docs/4.17.10#uniqWith

acesmndr
  • 8,137
  • 3
  • 23
  • 28