gpt4 book ai didi

javascript - 如何返回数组中重复字符串的数组?

转载 作者:行者123 更新时间:2023-11-28 11:12:44 25 4
gpt4 key购买 nike

我需要一个函数,它接受一个数组并返回一个包含所有重复项的数组。我更喜欢使用 underscore如果可能的话。

给定数组:

[
"apple",
"apple",
"pear",
"pear",
"kiwi",
"peach"
]

我需要返回一个数组

[
"apple",
"pear"
]

我发现的许多方法都会返回 bool 值,而不是重复项的数组。

例如

var fruits = ["apple","apple"];
var uniq_fruits = _.uniq(fruits);
var duplicates_exist = (fruits.length == uniq_fruits.length);

最佳答案

您可以使用_.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();

演示:http://jsfiddle.net/ambiguous/gKmfh/1/

关于javascript - 如何返回数组中重复字符串的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18279949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com