Reputation: 15498
I have an array that contains all ids and an array that holds all valid ids.
I just want to retrieve the invalid ids.
It could obviously be done by for loops, but if possible I'd like to do it using the .filter() method to keep it short and maybe more transparent.
The problem is that the array containing the valid ids looks a lot different fron the array that contains all ids. Let me show you:
var allIds = ["1673","2456","8977","5467"];
var validIds = [ {_id: "2456"}, {_id: "5467"} ];
var invalidIds = []; //as non-associative array
invalidIds = allIds.filter(function(x) { return validIds[x]["_id"].indexOf(x) < 0 });
console.log(invalidIds); //Uncaught TypeError: Cannot read property '_id' of undefined
Is there a way to fix that?
Upvotes: 1
Views: 68
Reputation: 21881
Array.prototype.filter
+ Array.prototype.some
var allIds = ["1673", "2456", "8977", "5467"];
var validIds = [{_id: "2456"}, {_id: "5467"}];
var invalidIds = allIds.filter(function (id) {
return !validIds.some(function (validId) {
return validId._id === id;
});
});
console.log(invalidIds); // ["1673", "8977"])
Upvotes: 2
Reputation: 25310
If you really insist on not using for-loops, you could, but it would be better to, since it would allow you to short-circuit the checking once you find a match.
var allIds = ["1673","2456","8977","5467"];
var validIds = [ {_id: "2456"}, {_id: "5467"} ];
var invalidIds = allIds.filter(function (id) {
return !validIds.reduce(function (contains, item) {
return contains || (item._id === id);
}, false);
}); //["1673", "8977"]
Upvotes: 3