Skip to content
Advertisement

Comparing one array to another then adding the missing objects from the second array to the first

I want to compare two object arrays from the WordCount class and add missing elements from the second array to the first one. My method below converts the first to a list. After that, the for loops check for the same words.

The tracker number is incremented if the same string is detected, and if the tracker remains 0 after the for loop, the object is then added to the first list, as it doesn’t exist in the first list. The count of this object is then set to 0.

Lastly, the list is converted back to an array. The problem is that this only returns 3 objects.

In theory, the list with a toString-method should look like this:

JavaScript

The WordCount Class:

JavaScript

Main method (in another class):

JavaScript

Advertisement

Answer

You need to reset the tracker every loop, not just when you find a new item.

I also rewrote your code to use lists from the start instead of converting arrays

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement