1

I have an array of user objects called allUsers and I need to check each object in it with the groupId which is passed to the function and return userNames which have the passed groupId.

I attempted this in the following manner.

vm.setNames=function(groupId){
        var products = "";
        angular.forEach(vm.allUsers,function (f) {
            if(f.groupId==groupId){
                vm.user=f;
                users= users+','+" "+vm.user.userName;
            }
        })

        return users= ;
    }

I want to have it in a map with group id as the key and relevant user names as values and return the relevant user names. How can I do that?

1 Answer 1

3

You can easily achieve that using the Array.reduce prototype function:

var allUsers = [
  { groupId: 1, userName: 'mario' },
  { groupId: 1, userName: 'luigi' },
  { groupId: 2, userName: 'peach' },
  { groupId: 2, userName: 'koopa' }
]

var getNames = function getNames(groupId, users) {
  return users.reduce(function(res, u) {
    if (u.groupId === groupId) {
      res = res + (res.length > 0 ? ', ' : '') + u.userName
    }
    return res
  }, '')
}

console.log(getNames(1, allUsers))
Sign up to request clarification or add additional context in comments.

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.