0

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.