I have a multidimensional array with values like this:
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]
];
I would like to extract unique users ID but keep the entries with email in the column index 1. If given user ID has no email than use the last row with given user ID. All the other columns for selected rows should kept in the output.
The result for the values above should look like this:
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
];
So far I have a script that removes duplicities:
// 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;
}
How can I ensure the rows with email are returned?