I am encountering an issue with an array that contains duplicate elements
let myArray=[
{role: "role-1", deviceId: ""},
{role: "role-2", deviceId: "d-2"},
{role: "role-3", deviceId: "d-3"},
{role: "role-1", deviceId: "d-1"},
{role: "role-2", deviceId: ""},
{role: "role-4", deviceId: ""}
{role: "role-5", deviceId: ""}
]
My goal is to eliminate the duplicate roles from the array, keeping only one role for each distinct role-value pair where the deviceId is not empty(""), and retain only one duplicate if the deviceId is empty in this manner.
myArray=[
{role: "role-1", deviceId: "d-1"},
{role: "role-2", deviceId: "d-2"},
{role: "role-3", deviceId: "d-3"}
{role: "role-4", deviceId: ""}
{role: "role-5", deviceId: ""}
]
The function I have written attempts to solve this issue:
function dedupeByKey(arr, key) {
const temp = arr.map(el => el[key]);
return arr.filter((el, i) =>
temp.indexOf(el[key]) === i
);
}
console.log(dedupeByKey(myArray, 'role'));
However, the current implementation does not prioritize deviceIds with values, resulting in roles with empty(deviceId) being included. How can I address this issue?