In my angular project i have a DataSource like
[
{id: "1", name: "John", age: "23", gender:"M", Role: "Student"},
{id: "2", name: "Smith", age: "24", gender:"M", Role: "Teacher"},
{id: "3", name: "Jeff", age: "23", gender:"M", Role: "Student"},
{id: "4", name: "Ronald", age: "25", gender:"M", Role: "Teacher"},
{id: "5", name: "Ronak", age: "23", gender:"M", Role: "Student"}
]
I need to check if any two or more lines of data are same or not based on multiple conditions. Eg : If any two lines have same age and gender and Role then return their Names
So the Expected Output will be
[John,Jeff, Ronak]
Since they share the same age, gender and Role else
[]
I tried to group the array, but I didn't find any solution to group it using multiple conditions, then tried nested loops, but seems inefficient and the results were not as expected.
You could take a joined key for the wanted properties, collenct the names for the group and return all names who are in a group with three or more items.
var data = [{ id: "1", name: "John", age: "23", gender: "M", Role: "Student" }, { id: "2", name: "Smith", age: "24", gender: "M", Role: "Teacher" }, { id: "3", name: "Jeff", age: "23", gender: "M", Role: "Student" }, { id: "4", name: "Ronald", age: "25", gender: "M", Role: "Teacher" }, { id: "5", name: "Ronak", age: "23", gender: "M", Role: "Student" }],
keys = ['age', 'gender', 'Role'],
groups = data.reduce((r, o) => {
const key = keys.map(k => o[k]).join('|');
r[key] = r[key] || [];
r[key].push(o.name);
return r;
} , {}),
result = Object.values(groups).flatMap(a => a.length >= 3 ? a : []);
console.log(result);
console.log(groups);