Lucky
Lucky

Reputation: 51

Remove duplicate nested objects in array using Lodash

I have an array which looks like below

var nestedArray = [
  { id: 1, filter: { type: "nestedArray", name: "5" } },
  { id: 2, filter: { type: "nestedArray1", name: "6" } },
  { id: 3, filter: { type: "nestedArray", name: "5" } }
];

Now here I have a duplicate object, I just want to identify the duplicates using a Lodash method. Any help is appreciated.

Have already tried map, filter options but need something in Lodash method.

Upvotes: 0

Views: 993

Answers (2)

bruteforcecat
bruteforcecat

Reputation: 100

So u want to reject duplicate ones by value in filter key?

_.uniqWith(nestedArray, (x, y) => _.isEqual(x.filter, y.filter), myArray)

If you have the flexibility to use Ramda instead, it could be more concise like because of every functions are auto-curried

const rejectDuplicateFilter = R.uniqWith(R.eqProps('filter'));
rejectDuplicateFilter(myArray)

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222572

You can use reject with a Property.

var myArray = [
  {
    "id": 1,
    "filter": {
      "type": "nestedArray",
      "name": "5"
    }
  },
  {
    "id": 2,
    "filter": {
      "type": "nestedArray1",
      "name": "6"
    }
  },
  {
    "id": 3,
    "filter": {
      "type": "nestedArray",
      "name": "5"
    }
  }
];

var result = _.reject(myArray, ['filter.name', '5']);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Upvotes: 1

Related Questions