简体   繁体   English

使用lambda查找数组中最频繁的数字,并使用JavaScript查找正则表达式

[英]Find the most frequent number in an array using lambda and regular expressions using JavaScript

I know this question has been asked several times, however I didn't find the desired solution. 我知道这个问题已经被问了好几次,但我没有找到所需的解决方案。

My task is to find the most frequent number in an array. 我的任务是找到数组中最频繁的数字。 First I have to convert to number because our input is given as strings. 首先,我必须转换为数字,因为我们的输入是以字符串形式给出的。 After that I sort the array with the lambda expression. 之后,我使用lambda表达式对数组进行排序。 (I don't understand how it works, I just know it does). (我不知道它是如何工作的,我只是知道它能工作)。 And now I want to filter the array [ 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 4, 9, 13 ] so only [4, 4, 4, 4, 4] is left. 现在我想过滤数组[1,1,1,2,2,3,3,4,4,4,4,4,9,13]所以只有[4,4,4,4,4]离开了。 I would like to use either .filter or .reduce . 我想请使用.filter.reduce

function z(input) 
{
let numbers = input.map(n => +n)
                   .sort((a, b) => a - b)
                   .filter();

console.log(numbers);
}
z(['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3']);

Also if someone can explain: 另外,如果有人可以解释:

function mode(arr){
    return arr.sort((a,b) => 
          arr.filter(v => v===a).length 
        - arr.filter(v => v===b).length
    ).pop();
}

mode(['pear', 'apple', 'orange', 'apple']); // apple

The callback on arr.sort takes two parameters a and b however after that I cannot understand what is going on. 在arr.sort上的回调带有两个参数a和b,但是在那之后我不明白发生了什么。

In fact any guide on how to use lambda will be appreciated. 实际上,任何有关如何使用lambda的指南都将受到赞赏。

You could use a Map for collecting the elements, with the same value and take a single loop approach by checking the lenght of the array and check the actual length against the previously store result. 您可以使用Map来收集具有相同值的元素,并通过检查数组的长度并根据先前存储的结果检查实际长度来采取单循环方法。

This approach take the possibility in account if more than one value has the same length, then both all arrays are returned with the maximum length. 如果有多个值具有相同的长度,则此方法考虑了可能性,然后所有两个数组都以最大长度返回。

 const z = a => { var m = new Map; return a.reduce((r, v, i) => { // create map var array = m.get(v) || m.set(v, []).get(v); // get/create array array.push(v); // push value if (!i || r[0].length < array.length) { // take first or check return [array]; // return array } if (r[0] !== array && r[0].length === array.length) { // prevent push same a r.push(array); // push with same len } return r; }, undefined); }; console.log(z(['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'])); console.log(z(['pear', 'apple', 'orange', 'apple'])); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

First of all I don't think you need to sort the array if you traverse it until its end? 首先,如果遍历数组直到结束,我不认为需要对数组进行排序?

function z(input) {
    let map = new Map;
    let numbers = input.map(i => parseInt(i))
                   //.sort((a, b) => a - b)
                   .forEach(e => {
                        map.set(e, (map.get(e) || 0) + 1);
                   });

    return Array.from(map).reduce((a, b) => a[1] > b[1] ? a : b)[0];
}

Explanation: 说明:

  1. Create a Map which can you use to set how many times your number appears in the array. 创建一个地图,您可以使用它来设置您的数字出现在数组中的次数。
  2. Use parseInt to transform each element of the array to a Number 使用parseInt将数组的每个元素转换为Number
  3. For each item in the array (which now has Numbers instead of Strings) you need to get the number of occurrences from the Map (using get function) and then set it back to the Map using the set function with the increamented value. 对于数组中的每个项目(现在具有数字而不是字符串),您需要从Map中获取出现的次数(使用get函数),然后使用带有隐含值的set函数将其设置回Map。 (map.get(e) || 0) is used in case this is the first time you encounter this number. (map.get(e)|| 0)会在您第一次遇到此数字时使用。
  4. In the end you can extract the content of the map using Array.from which will give you a jagged array (like [[1, 2], [3, 4], [4, 5]]). 最后,您可以使用Array。从中提取地图的内容,这将为您提供一个锯齿状的数组(例如[[1、2],[3、4],[4、5]])。 Each inner array will hold a pair of (number, occurrences). 每个内部数组将包含一对(数量,出现次数)。 You need to take the the pair which has the highest value in the second item of the pair which means 5 in the jagged array example and extract the first item of this pair. 您需要在对的第二个项中选取具有最高值的对,这意味着在锯齿状数组示例中为5,并提取该对的第一项。 You do it using the reduce function of the array. 您可以使用数组的reduce函数来实现。 The reduce function gets two items in the array and expects to return a value that has the same shape of the items that entered this function something like this reduce(a: A, b: A) => A which means a function that accepts two arguments of type A and return an instance of type A. In your example it is: reduce(a: [Int, Int], b: [Int, Int]) => [Int, Int] which means gets two parameters of type array and returns an array. reduce函数在数组中获取两个项目,并期望返回与进入此函数的项目具有相同形状的值,如reduce(a: A, b: A) => A ,这意味着该函数接受两个类型A的参数并返回类型A的实例。在您的示例中是: reduce(a: [Int, Int], b: [Int, Int]) => [Int, Int] ,这意味着获取两个类型为参数的参数数组并返回一个数组。

So the reduce function checks whether the first array has a greater number in the second index then the second array in the second index. 因此reduce函数会检查第二个索引中的第一个数组是否比第二个索引中的第二个数组具有更大的数字。 If yes it returns the first array and not the value in the second index, otherwise the second array. 如果是,则返回第一个数组,而不返回第二个索引中的值,否则返回第二个数组。 Because the reduce function output must be the same type of each one of its arguments than the type of the return value is also an array which has the number in its first index and the occurences in the second so you need to get the value from the first index. 因为reduce函数输出的每个参数的类型必须与返回值的类型相同,所以返回值也是一个数组,该数组的第一个索引中包含数字,第二个索引中包含出现的数据,因此您需要从第一个索引。

You can find the most frequent element in an array like this: 您可以在数组中找到最常见的元素,如下所示:

 function z(arr) { return Object.entries(arr.reduce((res, v) => { if(v in res) res[v]++; else res[v] = 1; return res; }, {})).sort((a, b) => a[1] < b[1])[0][0]; } let a = z(['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3']); console.log(a); 

Explanation: 说明:

  1. The call to arr.reduce serves to count the occurrences of every element in the arr . arr.reduce的调用用于计算arr中每个元素的出现次数。
  2. We then convert the object from arr.reduce to a 2D array like [[key, value]] using Object.entries . 然后[[key, value]]使用Object.entries将对象从arr.reduce转换为2D数组,例如[[key, value]]
  3. We then sort the Object.entries array in descending order based on the second element of each sub array. 然后,根据每个子数组的第二个元素,以降序对Object.entries数组进行排序。 (This element is the value part) (此元素是值部分)
  4. We then pick the first element in the sorted array, and return the key part of that element [0][0] . 然后,我们选择排序数组中的第一个元素,并返回该元素的关键部分[0][0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM