How to filter a dictionary by value in JavaScript?

You could use reduce again to achieve that in plain JavaScript:

var filtered = Object.keys(dict).reduce(function (filtered, key) {
    if (dict[key] > 1) filtered[key] = dict[key];
    return filtered;
}, {});

With some ES6 features, such as arrow functions, spread syntax, Object.entries, … it can look like this:

var filtered = Object.assign({}, ...
    Object.entries(dict).filter(([k,v]) => v>1).map(([k,v]) => ({[k]:v}))
);

Or using the newer Object.fromEntries:

var filtered = Object.fromEntries(Object.entries(dict).filter(([k,v]) => v>1));

Using Lodash

There were a few issues with your attempt with lodash:

  • _.find is not intended for returning an object that takes a selection of key/values from a given object. You would need _.pickBy for that.
  • Your object values do not have a frecuency property; they are primitive values, so you should just have to return user > 1

Lodash code:

var filtered = _.pickBy(dict, function(user) {
  return user > 1;
});

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)