3

For a list like (with many many entries):

-
    id: cs13157
    name: 'Current Load'
-
    id: cs1085
    name: 'Check CPU'
-
    id: cs1070
    name: Uptime
-
    id: cs1070
    name: 'Total Processes'

I've got a .countBy for ids that is returning some counts that are greater than 1 and some equal to 1. I only care about the greater than 1 values, since that indicates a problem. But since countBy is returning a big object, I have to loop the hash table values:

counts = ld(list).countBy('id').value();
for (k in counts) {
  v = counts[k];
  if (!(v > 1)) {
    continue;
  }
  logger.error("found duplicate value for ID " + k);
  errored = true;
}
// throw if errored is true 

This seems a like too much code but I can't see a way to quickly do this with lodash. I could pluck/map/filter to find the errant values. There's plenty of ways to do this but I'm wondering if there's a way to only get the list of IDs with a count greater than one with lodash and not with a loop.

SSCE:

  var arr, keys, ld, s;

  s = "- {id: 2240errorapp, name: 'app error count'}\n- {id: 2240errorinf, name: 'infrastructure error count'}\n- {id: '2112', name: calls}\n- {id: '2112', name: calls}\n- {id: 2112v, name: violations}\n- {id: 2112avg, name: 'average response time'}\n- {id: 2112errorapp, name: 'app error count'}\n- {id: 2112errorinf, name: 'infrastructure error count'}";

  ld = require('lodash');

  arr = (require('yamljs')).parse(s);

  keys = ld(arr).countBy('id').filter(function(k, v) {
    return k[v] > 1;
  }).value();

  console.dir(keys);

Expected value: ['2112'] (the duplicate). Actual value: [].

djechlin
  • 59,258
  • 35
  • 162
  • 290
jcollum
  • 43,623
  • 55
  • 191
  • 321

1 Answers1

3
counts.pick(function(v) { return v > 1; });

pick, not filter. Also v > 1 not k[v] > 1 as in your code.

filter wants an array of objects, not an object with many uniform keys. pick likes to work with object properties and filter out keys.

My answer is a duplicate of this question but I wouldn't recommend closing this question since there's more than one way to solve this problem.

Community
  • 1
  • 1
djechlin
  • 59,258
  • 35
  • 162
  • 290