如何在不改变任何内容的情况下找到数组中最常出现的项目?

时间:2018-05-05 01:47:16

标签: javascript functional-programming immutability

我想知道如何在不使用immutable.js的情况下在纯javascript中的不可变实现中重构此代码。

var arr1=[3, 'oo', 'oo', 'oo', 2, 3, 'oo', 3, 'oo', 2, 4, 9, 3];
var mf = 1;
var m = 0;
var item;
for (var i=0; i<arr1.length; i++)
{
    for (var j=i; j<arr1.length; j++)
    {
            if (arr1[i] == arr1[j])
             m++;
            if (mf<m)
            {
              mf=m; 
              item = arr1[i];
            }
    }
    m=0;
}
console.log(item+" ( " +mf +" times ) ");

2 个答案:

答案 0 :(得分:1)

看起来你正在尝试找到数组中最常出现的项目。使用reduce计算每个元素的重复次数,并找到最大重复次数。

在缩小时,请确保每次都为累加器返回 new 对象,这样就不会发生变异。

const arr1 = [3, 'oo', 'oo', 'oo', 2, 3, 'oo', 3, 'oo', 2, 4, 9, 3];
const reps = arr1.reduce((accum, item) => {
  const newCount = (accum[item] || 0) + 1;
  return { ...accum, [item]: newCount };
}, {});
const maxTimes = Math.max.apply(null, Object.values(reps));
const [recordItem] = Object.entries(reps).find(([, val]) => val === maxTimes);

console.log(recordItem + " ( " + maxTimes +" times ) ");

如果您需要识别与该记录匹配的所有项,请使用filter代替find

const arr1 = [3, 'oo', 'oo', 'oo', 2, 3, 'oo', 3, 'oo', 2, 4, 9, 3, 3];
const reps = arr1.reduce((accum, item) => {
  const newCount = (accum[item] || 0) + 1;
  return { ...accum, [item]: newCount };
}, {});
const maxTimes = Math.max.apply(null, Object.values(reps));
const recordItems = Object.entries(reps)
  .filter(([, val]) => val === maxTimes)
  .map(([key, val]) => key);

console.log(recordItems.join(', ') + " ( " + maxTimes +" times ) ");

答案 1 :(得分:1)

使用Map().reduce(),您可以创建非常功能方法:

&#13;
&#13;
const array = [3, 'oo', 'oo', 'oo', 2, 3, 'oo', 3, 'oo', 2, 4, 9, 3]

const maxOccurences = array => Array.from(
  array.reduce(
    (map, value) => map.set(
      value,
      map.has(value)
        ? map.get(value) + 1
        : 1
    ),
    new Map()
  ).entries()
).reduce(
  (max, entry) => entry[1] > max[1] ? entry : max
).reduce(
  (item, count) => ({ item, count })
)

console.log(maxOccurences(array))
&#13;
&#13;
&#13;

并不是我建议在生产代码中执行此操作,但您可以修改Array.prototype以将此功能扩展为数组的成员方法以方便:

&#13;
&#13;
const array = [3, 'oo', 'oo', 'oo', 2, 3, 'oo', 3, 'oo', 2, 4, 9, 3]

Object.defineProperty(Array.prototype, 'max', {
  value () {
    return Array.from(
      this.reduce(
        (map, value) => map.set(
          value,
          map.has(value)
            ? map.get(value) + 1
            : 1
        ),
        new Map()
      ).entries()
    ).reduce(
      (max, entry) => entry[1] > max[1] ? entry : max
    ).reduce(
      (item, count) => ({ item, count })
    )
  },
  configurable: true,
  writable: true
})

console.log(array.max())
&#13;
&#13;
&#13;