'JS find array of String and Array Object without duplicates
I had a lists of duplicate array of String and array of object. I want to find the property into one particular object of array uniquely without duplication of array object. If can done in lodash library, it would be awesome.
const arr1 = ['test@email', 'test2@email']
const arr2 = [{ id: 1, email: 'test@email' }]
Expected result
['test2@email']
this is what I done so far
By turning arr1 into object frist so I can compare with arr2
const emailLists = _.map(arr, function (item) {
console.log(item)
return { email: item }
})
then merge them to together and used uniq to remove duplicates
const merge = _.unionBy(array1, array2, 'email')
const result _.uniq(merge, 'email');
I think it still not a good process and not clean
Solution 1:[1]
You can do it without lodash
const arr1 = ['test@email', 'test2@email']
const arr2 = [{ id: 1, email: 'test@email' }]
const emailToDelete = arr2.map(a => a.email)
const result = arr1.filter(e => !emailToDelete.includes(e))
console.log(result)
Solution 2:[2]
You can use lodash chain to solve that:
const result = _([...arr1, ...arr2.map(i => i.email)]) // ['test@email', 'test2@email', 'test@email']
.countBy() // { test@email: 2, test2@email: 1 }
.pickBy(count => count === 1) // { test2@email: 1 }
.keys() // ['test2@email']
.value();
Solution 3:[3]
You can use filter on the first array and check that an email address matches with some of your objects in the second array. So even if it matches with multiple objects, the matching email will only be in the output once.
I want to find the property into one particular object of array uniquely without duplication of array object
So then your expected output is wrong, as you provide an email that is not found in the object array. I guess that was a typo in your question.
const arr1 = ['test@email', 'test2@email']
const arr2 = [{ id: 1, email: 'test@email' }]
const result = arr1.filter(search => arr2.some(({email}) => email == search));
console.log(result);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R4ncid |
| Solution 2 | hoangdv |
| Solution 3 | trincot |
