marked-down
marked-down

Reputation: 10428

Remove objects from array based on keys & properties in another object?

I have the following object, where the property key is set to a username and the property value is set to a count of the number of times they appear, and an array containing a list of objects with properties of UserId, and UserName:

peopleWhoAppear = { "Edward": 5, "Charlotte": 2, "Michael": 9, "Andy": 6 }

siteUsers = [ 
  { UserId: 1842, UserName: "Sam" }, 
  { UserId: 2943, UserName: "Charlotte" }, 
  { UserId: 1842, UserName: "Richard" },
  { UserId: 2916, UserName: "Ivan" },
  { UserId: 2073, UserName: "Paul" },
  { UserId: 1842, UserName: "Theo" }
  ...
]

I would like to remove all objects from the siteUsers array where the UserName matches a property key in the peopleWhoAppear object if the property value matches a certain number (it could be 5 or 8) and return the remaining results to another array. I've been stuck on this for 6 hours over 2 days now and I've not made any progress.

I've tried varies permutations and loops of .filter and .splice, but with no success. For example:

 for (var UserName in peopleWhoAppear) {
   if (peopleWhoAppear[UserName ] === count) {
                siteUsers.filter(function (person) {
                    console.log(person);
                    return person.UserName !== verifier;
                }));
     }
 }

How can I accomplish this? I don't have access to any libraries apart from jQuery so things like Underscore are not useful here.

Upvotes: 0

Views: 990

Answers (2)

Bergi
Bergi

Reputation: 665574

I've tried varies permutations and loops of .filter and .splice, but with no success.

You will only need filter:

return siteUsers.filter(function(obj) {
    var user = obj.UserName;
    return !(user in peopleWhoAppear && peopleWhoAppear[user] == count);
});

This will get you a new array, with all the users that did not appear in peoplWhoAppear or had the wrong count in there.

Upvotes: 4

Daniel Robinson
Daniel Robinson

Reputation: 3387

Filter() doesn't change the array, it returns a new one. If you want to iteratively filter the array, you have to set it to the return value of filter() each time.

// copy the array
var newSiteUsers = siteUsers.slice(0)  

for (var UserName in peopleWhoAppear) {
   if (peopleWhoAppear[UserName ] === count) {
                newSiteUsers = newSiteUsers.filter(function (person) {
                    console.log(person);
                    return person.UserName !== UserName;
                }));
     }
 }

console.log(newSiteUsers);

Upvotes: 2

Related Questions