I have an array containing duplicate elemnets
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: ""}
]
I want to remove the duplicate roles and have array which contains roles without empty("") deviceIds and if deviceId is empty keep only one role without duplicates in this way
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: ""}
]
I have written the function in this way
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'));
But in the result, its not checking to give priority for deviceId with values and role with empty deviceId is getting added. How to fix this?
role-2havedeviceId: "d-21"?role-3twice in the result while at the beginning you had one?