问题描述
我有一个包含重复elemnet的数组
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: ""}
]
我想删除重复的角色,并使用包含不带Empty()deviceIds的角色的数组,如果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'));
但是结果是,它没有检查是否为具有值的deviceId和具有空deviceId的角色赋予优先级为被添加。如何解决此问题?
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?
推荐答案
您可以使用reduce并默认使用object,如果需要,可以将其转换为array
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)
这篇关于JS过滤器数组根据条件删除重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!