Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Filter array to remove duplicate values based on condition

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?

like image 836
pupil Avatar asked Dec 18 '25 17:12

pupil


1 Answers

You can use reduce with default to object, and if you need, you can convert it to array at the end.

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: ""}
]

const res = myArray.reduce((agg, itr) => {
  if (agg[itr.role]) return agg // if deviceId already exist, skip this iteration
  agg[itr.role] = itr.deviceId  // if deviceId not exist, Add it
  return agg
}, {})

let make_array = Object.keys(res).map(key => { return { role: key, deviceId: res[key] }})

console.log(make_array)
like image 109
omri_saadon Avatar answered Dec 20 '25 07:12

omri_saadon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!