如何获得数组的最不频繁项-JavaScript? [英] How to get least frequent item of array - javascript?

查看:62
本文介绍了如何获得数组的最不频繁项-JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下函数来获取数组中最频繁出现的项目:

I'm using the following function to get the most frequent item of an array:

Array.prototype.array_most_frequent = function()  {
  var m=0, mf=0;
  for (var i=0; i<this.length; i++) {
          for (var j=i; j<this.length; j++)
          {
            if (this[i] == this[j]) m++;
            if (mf<m) {mf=m; item = this[i]; }
          }
          m=0;
  }
  return item;
}

工作正常-但是如何获取数组中最稀有的项?

Works fine - but how to get the rarest item of an array?

例如 var array = [2,1,2,5,5] 应该返回' 1 '.

是否有一种简便的方法可以访问阵列中频率最低的项目?

Is there an easy way to the least frequent item of my array?

谢谢.

推荐答案

一种创建阵列#减少.然后展开地图以获取条目,并将条目减少为出现次数最少的条目:

An ES6 solution that creates a Map of occurrences using Array#reduce. Then spread the map to get the entries, and reduce the entry to the entry with the smallest number of occurrences:

const array=[2,1,2,5,5];

const result = [...array.reduce((r, n) => // create a map of occurrences
    r.set(n, (r.get(n) || 0) + 1), new Map()
  )]
  .reduce((r, v) => v[1] < r[1] ? v : r)[0]; // get the the item that appear less times


console.log(result);

这篇关于如何获得数组的最不频繁项-JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆