英文:
Get unique values corresponding to the keys from an array of objects in JavaScript
问题
我的数组如下所示:
const arr1 = [
{
"Param1": "20",
"Param2": "8",
"Param3": "11",
"Param4": "4",
"Param5": "18",
"Param6": "20",
"Param7": "8"
},
{
"Param6": "21",
"Param7": "8",
"Param8": "11",
"Param9": "4",
"Param10": "18"
},
{
"Param1": "20",
"Param2": "8",
"Param3": "10"
}
]
我想要删除对象中存在的重复键值对。
期望结果:
arr1 = [
{
"Param1": "20",
"Param2": "8",
"Param3": "11",
"Param4": "4",
"Param5": "18",
"Param6": "20",
"Param7": "8"
},
{
"Param6": "21",
"Param8": "11",
"Param9": "4",
"Param10": "18"
},
{
"Param3": "10"
}
]
期望的输出是一个包含具有唯一键值对的对象的数组。如何获得这样的数组?
英文:
My array looks like this
const arr1 = [
{
"Param1": "20",
"Param2": "8",
"Param3": "11",
"Param4": "4",
"Param5": "18",
"Param6": "20",
"Param7": "8"
},
{
"Param6": "21",
"Param7": "8",
"Param8": "11",
"Param9": "4",
"Param10": "18"
},
{
"Param1": "20",
"Param2": "8",
"Param3": "10"
}
]
I wanted to remove the duplicate key value pairs existing in the objects.
Expected result:
arr1 = [
{
"Param1": "20",
"Param2": "8",
"Param3": "11",
"Param4": "4",
"Param5": "18",
"Param6": "20",
"Param7": "8"
},
{
"Param6": "21",
"Param8": "11",
"Param9": "4",
"Param10": "18"
},
{
"Param3": "10"
}
]
The desired output is an array containing objects having unique key value pairs. How can I get such an array?
答案1
得分: 2
Algorithm:
- 创建一个以
{param: {value: boolean}}
格式的seen
映射,用于指示是否已经看到具有这个值的参数。 - 创建一个
result
数组,用于存储唯一的参数。 - 遍历输入数组,获取当前元素的键,并遍历这些键。
- 检查具有这个值的参数是否已经被看到,如果是,则忽略它;否则将其添加到
result
中并标记为已看到。 - 返回
result
数组。
Implementation:
const removeDuplicates = (arr) => {
return arr.reduce(
(acc, item) => {
acc.result.push(
Object.fromEntries(
Object.entries(item).filter(([key, value]) => {
acc.seen[key] = acc.seen[key] ?? {};
if (acc.seen[key][value]) return false;
acc.seen[key][value] = true;
return true;
}),
),
);
return acc;
},
{ seen: {}, result: [] },
).result;
};
英文:
Algorithm:
- Create a map
seen
in the format of{param: {value: boolean}}
which will indicate whether the param with this value was already seen - Create a
result
array that will store the unique params - Traverse through the input array, get the keys of the current element, and traverse through them.
- Check if the param with this value was already seen, if yes, ignore it; otherwise add it to the
result
and mark it as seen - Return the
result
array.
Implementation:
const removeDuplicates = (arr: Record<string, string>[]) => {
return arr.reduce<{
seen: Record<string, Record<string, boolean>>;
result: Record<string, string>[];
}>(
(acc, item) => {
acc.result.push(
Object.fromEntries(
Object.entries(item).filter(([key, value]) => {
acc.seen[key] = acc.seen[key] ?? {};
if (acc.seen[key][value]) return false;
acc.seen[key][value] = true;
return true;
}),
),
);
return acc;
},
{ seen: {}, result: [] },
).result;
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论