0

I have an array where the objects are generated from a push that is inside a function, when I try to view the objects directly in the array I am successful, but I am using forEach to add the number of times that an id uses the service, but the result always returns empty.

client.onMessage(async message => {

   count_commands.push({id:parseInt(regNumberPhone), age: 1});

});


const count_commands = [],
  hash = Object.create(null),
  result = [];

  count_commands.forEach(function (o) {
    if (!hash[o.id]) {
        hash[o.id] = { id: o.id, age: 0 };
        result.push(hash[o.id]);
    }
    hash[o.id].age += +o.age;
  });

to look de objects in count_commands

console.log(count_commands);
Return:
[ { id: 559892099500, age: 1 },
  { id: 559892099500, age: 1 },
  { id: 559892099500, age: 1 } ]

but to see the total sum of each id the array returns empty

console.log(result);
Return:

    {}

I need to return like:

[ { id: 559892099500, age: 3 } }

1 Answer 1

1

Your code is working as expected. i.e. the for loop will return the structure that you require. The problem I am going to guess is that you are registering an event handler that will populate the count_commands array only after the onMessage event has been received.

If you are trying to iterate the count_commands array prior to it being populated you will get back an empty result. I suspect there are other problems also if the console.log is returning {} instead of [].

You need to modify your code to something similar to as follows

const count_commands = [];
const result = [];
const hash = {};

client.onMessage(async message => {
   count_commands.push({id:parseInt(regNumberPhone), age: 1});
   updateResults();
});

function updateResults() {
  count_commands.forEach(function (o) {
    if (!hash[o.id]) {
        hash[o.id] = { id: o.id, age: 0 };
        result.push(hash[o.id]);
    }
    hash[o.id].age += +o.age;
  });
}
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.