I'm trying to remove duplicate items using lodash.js but I can't make it works properly.
This is the structure of an object in the array:
{
label: 'tagA',
value: 1
}
So let say I have this array:
var objectsArray = [
{
label: 'tagA',
value: 1
},
{
label: 'tagB',
value: 2
},
{
label: 'tagC',
value: 3
},
{
label: 'tagB',
value: 4
},
{
label: 'tagB',
value: 5
},
];
I made this piece of code with _.uniqBy() function from lodash.js to try to remove the elements of array with the same labels, but it dosn't work as I expected:
var uniq = _.uniqBy(objectsArray, function(o){
return o.label;
});
I based on some sample found here and there and lodash documentation of course but I have a lack of knowledge in this regard so any help it will super appreciate it.
Thanks.
To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.
Lodash's 'uniq' family of methods can be implemented in plain JS without trouble. Lodash is a very useful utility library that lets us work with objects and arrays easily.
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
To get duplicate values from an array with Lodash, we can use the countBy method to count the values. Then we call the JavaScript array's reduce method to get all the items that has count more than 1 and put them in an array.
Make sure that you use proper namings, that code works for me:
var arr = [
{
label: 'tagA',
value: 1
},
{
label: 'tagB',
value: 2
},
{
label: 'tagC',
value: 3
},
{
label: 'tagB',
value: 4
},
{
label: 'tagB',
value: 5
},
];
var uniq = _.uniqBy(arr, function(o){
return o.label;
});
console.log(uniq); // >> Returned an array with first 3 objects from array arr
If you want to make sure you can use uniqWith();
This works for me
var data = [
{
label: 'tagA',
value: 1
},
{
label: 'tagB',
value: 2
},
{
label: 'tagC',
value: 3
},
{
label: 'tagB',
value: 4
},
{
label: 'tagB',
value: 5
},
];
var filtered = _.uniqWith(data, function(first, second){
return first.label === second.label
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With