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: []
.