Tho*_*ggi 0 javascript arrays unique duplicates underscore.js
我需要一个接收数组的函数,并返回一个包含所有重复项的数组.如果可能的话,我更愿意使用下划线.
给定数组:
[
"apple",
"apple",
"pear",
"pear",
"kiwi",
"peach"
]
Run Code Online (Sandbox Code Playgroud)
我需要返回一个数组
[
"apple",
"pear"
]
Run Code Online (Sandbox Code Playgroud)
我发现的许多方法都会返回一个布尔值,而不是一个重复数组.
例如
var fruits = ["apple","apple"];
var uniq_fruits = _.uniq(fruits);
var duplicates_exist = (fruits.length == uniq_fruits.length);
Run Code Online (Sandbox Code Playgroud)
您可以使用_.countBy获取单词频率,然后用于_.reduce收集频率大于1的值:
function collect_dups(a, n, word) {
if(n > 1)
a.push(word);
return a;
}
var dups = _(words).chain()
.countBy()
.reduce(collect_dups, [])
.value();
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ambiguous/gKmfh/1/
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |