阵列中出现次数最多或首次选择 [英] Highest occurrence in an array or first selected

查看:98
本文介绍了阵列中出现次数最多或首次选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到一个数组值最高的值,如果有相同的出现次数,我应该得到相同出现次数的第一个选定值。

I'm trying to get the highest occurrence of a array value, and if there's an equal occurrence, I should get the first selected value of the equal occurrences.

示例:

var array = ['25','50','a','a','b','c ']

在这种情况下,我应该得到 a

In this case I should get a

var array = ['75','100','a','b','b','a']

在这种情况下,我还应该 a

In this case I also should get a

我已经完成了相当多的搜索,发现了一些有用的帖子,例如:

I've done my fair share of searching and found a couple of helpfull posts, these for example:

找到最常见的项目数组(不仅仅是字符串)

不知怎的,我似乎无法修改这些例子来工作我的情况。

Somehow I can't seem to modify these examples to work for my case.

现在我正在使用下面的代码,但它返回的是最后一次选择的相等,而不是第一次。 (信用卡 https://stackoverflow.com/users/1238344/emissary

Right now I'm using the code below, but its returning the last selected equal occurrence, instead of the first. (credit https://stackoverflow.com/users/1238344/emissary)

function mostFrequent(array){
  return array.sort(function(a,b){
    return array.filter(function(v){ return v===a }).length
      - array.filter(function(v){ return v===b }).length
  }).pop();
}

欢迎任何帮助。

推荐答案

你可以使用这样的东西:

You could use something like this:

function mostFrequent(array) {
    var map = array.map(function(a) {
        return array.filter(function(b) {
            return a === b;
        }).length;
    });

    return array[map.indexOf(Math.max.apply(null, map))];
}

首先,它会创建所有值的出现地图。接下来只需检查 Math.max 哪一个是最高的。检查 indexOf ,查找具有最高出现次数的第一个值,并返回原始数组中该索引的值。

First it creates a map of occurrences of all the values. Next just check with Math.max which one is the highest. Check the indexOf for the first value that has that highest occurences and return the value of that index in the original array.

如果ES2015是一个选项,你可以使用这个。它的代码更少。

If ES2015 is an option, you could use this one. It's less code.

function mostFrequent(array) {
    let map = array.map((a) => array.filter((b) => a === b).length);

    return array[map.indexOf(Math.max.apply(null, map))];
}

如果你在一个甚至允许传播运营商的地方( NodeJS v5及更高版本,Chrome 54)您可以替换 Math.max.apply(null,map) for Math.max(... map)

And if you're in a place where even the spread operator is allowed (NodeJS v5 and up, Chrome 54) you could replace Math.max.apply(null, map) for Math.max(...map)!

这篇关于阵列中出现次数最多或首次选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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