How to get distinct elements(case insensitive) from array of objects using lodash

I have an array that looks something like below,

[
  {
    "_id": "5e3ccb88c9b3027ef4977894",
    "name": "microsoft"
  },
  {
    "_id": "59ce020caa87df4da0ee2c77",
    "name": "Microsoft"
  },
  {
    "_id": "5e077c78bc0d663d7170ba1c",
    "name": "MICROSOFT"
  },
  {
    "_id": "608839e8d9271457814a7aa4",
    "name": "Microsoft "
  },
  {
    "_id": "5ecd46657ffa9b761a0e41cd",
    "name": "Microsoft  - MSN"
  },
  {
    "_id": "5dfb47adbc0d663d716fe25f",
    "name": "Microsoft  Alumni Foundation"
  }
]

now I need only one Microsoft, instead of these case combinations using lodash.

expected output,

[
  {
    "_id": "608839e8d9271457814a7aa4",
    "name": "Microsoft "
  },
  {
    "_id": "5ecd46657ffa9b761a0e41cd",
    "name": "Microsoft  - MSN"
  },
  {
    "_id": "5dfb47adbc0d663d716fe25f",
    "name": "Microsoft  Alumni Foundation"
  }
]

can anyone help me out with this? found many solution, but i need the case insensitive filter.

thanks in advance.

Answer

You can use _.filter, _.toLower and _.trim to do this.

We can keep a seen Set() of values, so we know which items we’ve seen before. And using _.toLower and _.trim before adding or checking this set we can make sure that the item is not a slight variation of another item in the array.

Like this:

let data = [ { _id: '5e3ccb88c9b3027ef4977894', name: 'microsoft' }, { _id: '59ce020caa87df4da0ee2c77', name: 'Microsoft' }, { _id: '5e077c78bc0d663d7170ba1c', name: 'MICROSOFT' }, { _id: '608839e8d9271457814a7aa4', name: 'Microsoft ' }, { _id: '5ecd46657ffa9b761a0e41cd', name: 'Microsoft  - MSN' }, { _id: '5dfb47adbc0d663d716fe25f', name: 'Microsoft  Alumni Foundation' }, ];

const testPrefixes = new Set();

let res = _.filter(data, (o) => {
  if (testPrefixes.has(_.trim(_.toLower(o.name)))) return false;
  else return testPrefixes.add(_.trim(_.toLower(o.name)));
});

console.log(res);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>