【发布时间】:2021-01-29 16:12:54
【问题描述】:
我有一个多维数组,其值如下:
let unfilteredArray = [
["1234", "no email entered", "other value", null, 7, "another value"],
["3333", "b@example.com", "another value", 2, 10, "something else"],
["1234", "a@example.com", "random value", 2, null, "something else"],
["4444", "c@example.com", "another value", 29, 3, "xxx"],
["5555", "abcd", "another value", 3, 41, "yyy"],
["1234", "another random text", "another value", 4, 8, "zzz"],
["5555", "efgh", "another value", null, 0, null]
];
我想提取唯一的用户 ID,但在列索引 1 中保留带有电子邮件的条目。如果给定的用户 ID 没有电子邮件,则使用给定用户 ID 的最后一行。所选行的所有其他列应保留在输出中。
上述值的结果应如下所示:
let unfilteredArray = [
["1234", "a@example.com", "random value", 2, null, "something else"],
["3333", "b@example.com", "another value", 2, 10, "something else"],
["4444", "c@example.com", "another value", 29, 3, "xxx"],
["5555", "efgh", "another value", null, 0, null] // no email for User ID 5555 => last 5555 row used
];
到目前为止,我有一个删除重复的脚本:
// index = index of the column with User ID
function removeDuplicates(array, index) {
// Gets only the first entry - the rest are removed
let filteredArray = [];
for (let i = 1; i < array.length; i++) {
let isDuplicate = false;
for (let j = i-1; j >= 0; j--) {
if (array[i][index] == array[j][index]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
filteredArray.push(array[i]);
}
}
return filteredArray;
}
如何确保返回带有电子邮件的行?
【问题讨论】:
-
请将表格转换为数组。
-
你可以按用户ID对数组进行分组,然后
.reduce每组到一个记录吗?如果您在示例数据中包含一个,我会试一试。 -
某些列可以包含空值。也许正因为如此,建议的解决方案不起作用?我更新了示例以尽可能接近真实案例。谢谢!
标签: javascript arrays sorting unique