I have an array that looks something like below,
JavaScript
x
27
27
1
[
2
{
3
"_id": "5e3ccb88c9b3027ef4977894",
4
"name": "microsoft"
5
},
6
{
7
"_id": "59ce020caa87df4da0ee2c77",
8
"name": "Microsoft"
9
},
10
{
11
"_id": "5e077c78bc0d663d7170ba1c",
12
"name": "MICROSOFT"
13
},
14
{
15
"_id": "608839e8d9271457814a7aa4",
16
"name": "Microsoft "
17
},
18
{
19
"_id": "5ecd46657ffa9b761a0e41cd",
20
"name": "Microsoft - MSN"
21
},
22
{
23
"_id": "5dfb47adbc0d663d716fe25f",
24
"name": "Microsoft Alumni Foundation"
25
}
26
]
27
now I need only one Microsoft, instead of these case combinations using lodash.
expected output,
JavaScript
1
15
15
1
[
2
{
3
"_id": "608839e8d9271457814a7aa4",
4
"name": "Microsoft "
5
},
6
{
7
"_id": "5ecd46657ffa9b761a0e41cd",
8
"name": "Microsoft - MSN"
9
},
10
{
11
"_id": "5dfb47adbc0d663d716fe25f",
12
"name": "Microsoft Alumni Foundation"
13
}
14
]
15
can anyone help me out with this? found many solution, but i need the case insensitive filter.
thanks in advance.
Advertisement
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:
JavaScript
1
5
1
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"}]
2
3
const result = _.uniqBy(arr, o => o.name.trim().toLowerCase())
4
5
console.log(result)
JavaScript
1
1
1
<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:
JavaScript
1
8
1
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"}]
2
3
const result = _.reverse(_.uniqBy(
4
_.reverse([arr]),
5
o => o.name.trim().toLowerCase()
6
))
7
8
console.log(result)
JavaScript
1
1
1
<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>