I have the following situation:
There are an undefined number of arrays. Each array contains some objects. Each of these objects has an id element, among some other elements.
//Example objects:
f = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'},
{'id': 3, 'name': 'c'}, {'id': 1, 'name': 'd'}, ...]
g = [{'id': 2, 'name': 'e'}, {'id': 4, 'name': 'f'},
{'id': 3, 'name': 'g'}, {'id': 4, 'name': 'h'}, ...]
h = ...
i = ...
I would like to filter out all the duplicates, not only inside every separate array, but also across the different arrays.
Edit: Two objects are a duplicate when their id element are the same. Precedence does not matter, first occurrence is fine for this.
I came up with the following function:
function uniqueObjects() {
var seen = [];
for (var i=0; i<arguments.length; i++) {
var arg = arguments[i];
for (var j=0; j<arg.length; j++) {
var elm = arg[j];
var key = elm['id'];
if (seen.indexOf(key) > -1) {
arg.pop(elm);
} else {
seen.push(key);
}
}
}
return arguments;
}
But this does not seem to work properly, since I got the following values:
{'0': [{'id': 1, 'name': 'a'},
{'id': 2, 'name': 'b'},
{'id': 3, 'name': 'c'}],
'1': [{'id': 2, 'name': 'e'},
{'id': 4, 'name': 'f'}]}
idor same all properties?