2

I have two arrays that I would like to compare and provide a count of the items in the master list.

The master list might look like this:

{ name: 'Jon', age: 34 },
{ name: 'Steve', age: 33 },
{ name: 'Mark', age: 34 },
{ name: 'Jon', age: 35 }

The Filter list gets all possible names / ages from the database. Some might not have any entries. Each of these lists are getting pulled from an API individually. I will combine them into one array:

{ users:
    [{ username: 'Jon' },
    { userName: 'Steve' },
    { username: 'Mark' },
    { username: 'Mike' }],
  ages:
    [{age: 33},
     {age: 34},
     {age: 35},
     {age: 36}]
}

What I would like to do is be able to count how many of each name I have

Jon - 2, Steve - 1, Mark - 1, Mike - 0

33 - 1, 34 - 2, 35 - 1

5
  • I've started through doing an angular.forEach loop based on the "master" list. I'm stuck trying to figure out best way to loop through each of the properties and comparing them to the filter list Jun 23, 2015 at 15:12
  • 1
    @JonHarding if you're using angular, please let users know that in your question Jun 23, 2015 at 15:13
  • This isn't specific to angular at all Jun 23, 2015 at 15:14
  • I know you can use js in angular, but it will be probably better to use angular function, no ? Jun 23, 2015 at 15:17
  • Don't you need to filter your master list before counting?
    – ericbn
    Jun 23, 2015 at 15:58

4 Answers 4

3

Here is a generic approach. You provide the data and the field you want to count.

var data = [
    { name: 'Jon',   age: 34 },
    { name: 'Steve', age: 33 },
    { name: 'Mark',  age: 34 },
    { name: 'Jon',   age: 35 }
];

function countUnique(items, property) {
    return items.reduce(function(map, item) {
        if (item.hasOwnProperty(property)) {
            map[item[property]] = (map[item[property]] || 0) + 1;
        }
        return map;
    }, {});
} 


console.log(countUnique(data, 'name')); // Object {Jon: 2, Steve: 1, Mark: 1}
console.log(countUnique(data, 'age'));  // Object {33: 1, 34: 2, 35: 1}


Filtering

If you want to filter a list of users by conditions, you can define an array of filter objects as seen below. When filtering a list of items, you usually will provide a predicate function to execute on the current item in the filter call. This function returns a boolean value which determines whether or not the item meets the conditions of the function.

var users = [
  { name: 'Jon',   age: 34 },
  { name: 'Steve', age: 33 },
  { name: 'Mark',  age: 34 },
  { name: 'Jon',   age: 35 }
];
var filters = [{
  name: 'users',
  predicate : function(user) {
    return [ 'Jon', 'Mark', 'Mike' ].indexOf(user.name) > -1;
  }
}, {
  name: 'ages',
  predicate : function(user) {
    return user.age >= 34 && user.age <= 36;
  }
}];

print(filterFactory(users, getFiltersByName(filters, ['users', 'ages'])));

function getFiltersByName(filters, names) {
  return filters.filter(function(filter) {
    return names.indexOf(filter.name) > -1;
  });
}
function filterFactory(items, filters) {
  return items.filter(function(item) {
    return filters.some(function(filter) {
      try { return filter.predicate.call(undefined, item); }
      catch (e) { throw new Error('predicate undefined for filter: ' + filter.name); }
    });
  });
}
function print(obj) {
  document.body.innerHTML = JSON.stringify(obj, undefined, '  ');
}
body { font-family: monospace; white-space: pre }

1

Something like this would do. Here is a fiddle http://jsfiddle.net/5jkqv6k3/

var data = [
  { name: 'Jon',   age: 34 },
  { name: 'Steve', age: 33 },
  { name: 'Mark',  age: 34 },
  { name: 'Jon',   age: 35 }
];

var key = function(obj) {
  // Some unique object-dependent key
  return obj.name; // Just an example
};

var dict = {};

for (var i = 0; i < data.length; i++) {
  if (dict[key(data[i])])
    dict[key(data[i])] = dict[key(data[i])] + 1;
  else
    dict[key(data[i])] = 1;
}

console.log(dict);

2
  • would you do this for each property rather than combining the filter into one list? Jun 23, 2015 at 15:24
  • @JonHarding yes it would be better combining into a list!. Updating my answer now.
    – meteor
    Jun 23, 2015 at 15:29
1

Using angularJs (because you're using it as you said) you can do this:

var countNamesList = {};
var countAgesList = {};
angular.forEach(masterList, function(value, index) {
    countNamesList[masterList[index].name] =
        (!angular.isUndefined(countNamesList[masterList[index].name])) ?
        countNamesList[masterList[index].name] + 1 : 1;
    countAgesList[masterList[index].age] =
        (!angular.isUndefined(countAgesList[masterList[index].age])) ?
        countAgesList[masterList[index].age] + 1 : 1;
});
console.log(countNamesList);
console.log(countAgesList);

JSFIDDLE

0

Mr. Polywhirl's answer is your best option on counting.

Now here's how you can filter:

var master = [ 
        { name: 'Jon', age: 34 },
        { name: 'Steve', age: 33 },
        { name: 'Mark', age: 34 },
        { name: 'Jon', age: 35 }
];
var filter = { 
    users: [ 
        { username: 'Jon' },
        { username: 'Mark' },
        { username: 'Mike' }
    ], ages: [
        { age: 34 },
        { age: 35 },
        { age: 36 }
    ]
};

function filterByNameAndAge(obj) {
    return filter.users.some(function(user) {
        return user.username === obj.name;
    }) && filter.ages.some(function(age) {
        return age.age === obj.age;
    });
}

console.log(master.filter(filterByNameAndAge));

Currently it accepts only objects with matching name and age. Replace the && inside filterByNameAndAge by || if it should accept objects with matching name or age.

1
  • unfortunately filter isn't returned as a string array Jun 23, 2015 at 15:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.