skip to Main Content

I have a large array (list of dictionaries) in javascript and I have to retrieve data from the array in a specific format here is an example of a snippet of the array

data = [{"userId":1, "completed":true},
        {"userId":1, "completed":false},
        {"userId":1, "completed":true},
        {"userId":2, "completed":false},
        {"userId":2, "completed":true}
]

what I had to do was retrieve the userId and the count of (completed) if its value is true
eg ouput = {1, 2} for userId:1
i tried filtering and looping but it doesn’t seem to work

2

Answers


  1. Sounds like you might want to user reduce and group them by userId. So maybe this:

    const data = [
        {"userId":1, "completed":true},
        {"userId":1, "completed":false},
        {"userId":1, "completed":true},
        {"userId":2, "completed":false},
        {"userId":2, "completed":true}
    ];
    
    const usersByCompleteds = data.reduce((retval, item) => {
      if (!retval[item.userId]) {
        retval[item.userId] = 0;
      }
      if(item.completed) {
          retval[item.userId] = retval[item.userId] + 1;
      }
      return retval;
    }, {});
    
    console.log(usersByCompleteds);
    
    Login or Signup to reply.
  2. Use the forEach method to loop through the array. For each object, it checks if completed value is true, and if so, increments the count for the corresponding userId in the userCounts object. The resulting userCounts object contains the counts of completed tasks for each user where completed is true.

    const data = [
      { userId: 1, completed: true },
      { userId: 1, completed: false },
      { userId: 1, completed: true },
      { userId: 2, completed: false },
      { userId: 2, completed: true }
    ];
    
    const userCounts = {};
    
    data.forEach(item => {
      if (item.completed) {
        const userId = item.userId;
        userCounts[userId] = (userCounts[userId] || 0) + 1;
      }
    });
    
    console.log(userCounts);

    You can make it a bit shorter, basically an arrow function expression.

    const data = [
      { userId: 1, completed: true },
      { userId: 1, completed: false },
      { userId: 1, completed: true },
      { userId: 2, completed: false },
      { userId: 2, completed: true }
    ];
    
    const userCounts = {};
    
    data.forEach(({userId, completed}) => completed && (userCounts[userId] = (userCounts[userId] || 0) + 1));
    
    console.log(userCounts);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search