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 lodash’s _.uniqBy(), which accepts a function that generates the matching criteria. In this case trim the string, and convert it to lower case:

const arr = [{"_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 result = _.uniqBy(arr, o => o.name.trim().toLowerCase())

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Since you want the last item in a series of duplicates, you can reverse the array, get the unique items, and then reverse it back:

const arr = [{"_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 result = _.reverse(_.uniqBy(
  _.reverse([...arr]), 
  o => o.name.trim().toLowerCase()
))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


Source: stackoverflow