我有两个包含字符串的数组。第二个数组只能包含第一个中的字符串,但是可以多次。我正在尝试在第二个数组中找到出现次数最少的单词。这里有一些例子:
const original = ['foo', 'bar', 'baz'];
const arr1 = ['foo', 'bar']; // => ['baz'] because 'baz' is 0 times in arr1.
const arr2 = ['foo', 'foo', 'bar']; // => ['baz'] because 'baz' is 0 times in arr2.
const arr3 = ['foo', 'foo', 'bar', 'bar', 'baz']; // => ['baz'] because 'baz' in 1 time in arr3.
const arr4 = ['foo', 'bar', 'baz']; // => ['foo', 'bar', 'baz']; because they are all the lowest (1 time).
const arr5 = ['foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz']; // => ['foo', 'baz'] because they are both only 2 times in arr5
您如何使用Ramda做到这一点? (或在JS中通常)?我觉得可以用R.countBy
来解决,但是我不知道如何获取所有具有最低值的键。
您可以使用R.countBy,但是您必须创建一个默认对象,其中originals
中的每个项目的值为0,然后合并它们。然后,找到最小值,并过滤original
数组:
const { chain, flip, zipObj, map, always, curry, pipe, countBy, identity, mergeRight, values } = R;
const getDefaults = chain(flip(zipObj), map(always(0)));
const countWithDefaults = curry((dflts, arr) => pipe(
countBy(identity),
mergeRight(dflts),
)(arr));
const fn = curry((orig, arr) => {
const counts = countWithDefaults(getDefaults(orig), arr);
const min = Math.min(...values(counts));
return original.filter(k => counts[k] === min);
});
const original = ['foo', 'bar', 'baz'];
const fnO = fn(original);
console.log(fnO(['foo', 'bar'])); // => ['baz'] because 'baz' is 0 times in arr1.
console.log(fnO(['foo', 'foo', 'bar'])); // => ['baz'] because 'baz' is 0 times in arr2.
console.log(fnO(['foo', 'foo', 'bar', 'bar', 'baz'])); // => ['baz'] because 'baz' in 1 time in arr3.
console.log(fnO(['foo', 'bar', 'baz'])); // => ['foo', 'bar', 'baz']; because they are all the lowest (1 time).
console.log(fnO(['foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'])); // => ['foo', 'baz'] because they are both only 2 times in arr5
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>