so I have an array containing some objects. I want to compare these objects with each other. If the fromId
AND the toId
properties are the same, it is an duplicate.
Example:
const data = [{
fromId: 1,
toId: 2,
finished: true
}, {
fromId: 1,
toId: 2,
finished: false
}, {
fromId: 5,
toId: 9,
finished: false
}, {
fromId: 1,
toId: 5,
finished: true
}, {
fromId: 2,
toId: 1,
finished: false
}];
$(document).ready(() => {
const duplicates = data.filter(x =>
data
.filter(y => y.fromId == x.fromId && y.toId == x.toId)
.length > 1
);
console.log(duplicates);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And I want to get the length of this data array but only with unique values. I tried to remove all duplicate values and found a solution here
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
const data = [1, 2, 3, 4, 5, 2, 2, 6, 7, 8, 2, 9, 2, 2, 2, 2, 2];
$(document).ready(() => {
const uniqueValues = data.filter((connection, index) => data.indexOf(connection) == index);
console.log(uniqueValues);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
but on this solution I just use indexOf
for the whole object. How can I compare the fromId
and toId
and remove the duplicate on same matches?
From the original array I would remove one
{
fromId: 1,
toId: 2,
finished: false
}
because the fromId
and toId
exist already at another object.