如何在JavaScript中按值过滤字典?

时间:2016-06-03 12:59:36

标签: javascript html lodash

我正在编写一个脚本来创建一个名为 dict 的字典,其中我存储了文本区域中某些单词的频率。我的数组看起来像这样:

var dict = removeArray.reduce(function(p,c) {
    if (p[c] === undefined) {
        p[c] = 1;
    } else {
        p[c]++;
    }
    return p;
}, {});

我想根据它们的值过滤这个字典的元素。我需要创建一个列表,其中包含值大于1的单词。我的字典看起来像这样:

{
    "92173": 6,
    "C": 6,
    "GJHGWO.NAYE": 1,
    "GJHGX4.NAYE": 1,
    "GJHGX6.NAYE": 1,
    "GJHGX8.NAYE": 1,
    "GJHGXA.NAYE": 1,
    "GJHGXC.NAYE": 1,
    "RBD": 10,
    "RBD3": 2,
    "SAMBORNSiPOSSSTHRa": 2,
    "SAMBORNSiPOSSSTHRa1": 2,
    "SAMBORNSiPOSSSTHRa2": 2,
    "X": 4,
    "X3": 2
}

为了实现我尝试使用lodash,如下:

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

但是自从我失败后我失败了:

undefined

我不知道如何恰当地使用lodash来过滤这个数组。

我的完整代码如下所示:



var splitWords = document.getElementById("texto").value.split(/[["\|~]/);
var removeArray  = _.remove(splitWords, function (word) {
    return word !== '' && word !== ' ' && word !== '\n'
});

var dict = removeArray.reduce(function(p,c) {
    if (p[c] === undefined) {
        p[c] = 1;
    } else {
        p[c]++;
    }
    return p;
}, {});
console.log(dict);

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

console.log(filtered)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<p id="demo"></p>
<textarea cols="150" rows="15" id="texto">
"RBD|X|RBD3|C|92173~GJHGWO.NAYE"
"SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX4.NAYE"
"SAMBORNSiPOSSSTHRa"
"RBD|X3|RBD3|C|92173~GJHGX6.NAYE"
"SAMBORNSiPOSSSTHRa1"
"RBD|X|RBD|C|92173~GJHGX8.NAYE"
"SAMBORNSiPOSSSTHRa2"
"RBD|X|RBD|C|92173~GJHGXA.NAYE"
"SAMBORNSiPOSSSTHRa2"
"RBD|X3|RBD|C|92173~GJHGXC.NAYE"
"SAMBORNSiPOSSSTHRa"
</textarea>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:18)

您可以再次使用reduce来实现纯JavaScript:

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

使用一些ES6功能,例如箭头功能,扩展语法,Object.entries,......它可能如下所示:

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

或使用较新的Object.fromEntries

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

使用Lodash

您尝试使用lodash时遇到了一些问题:

  • _.find不用于返回从给定对象中选择键/值的对象。你需要_.pickBy
  • 您的对象值没有frecuency属性;它们是原始值,因此您只需返回user > 1

Lodash代码:

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