简体   繁体   English

简单频率排序 - Codewars 挑战 - JavaScript

[英]Simple Frequency Sort - Codewars Challenge - JavaScript

For this CodeWars challenge , the idea is to sort the array by frequency of elements - from most occurring to least occurring.对于这个CodeWars challenge ,想法是按元素的频率对数组进行排序 - 从最多出现到最少出现。 So所以

solve([2,3,5,3,7,9,5,3,7]) = [3,3,3,5,5,7,7,2,9]

What I've done is turned the array into a string, created a frequency map, pushed the items from that map into a sorted array, and then pushed the numerical values from the sorted array into a final array.我所做的是将数组转换为字符串,创建频率 map,将 map 中的项目推入排序数组,然后将排序数组中的数值推入最终数组。

 function solve(arr){ let myString = JSON.stringify(arr).split(''); let newArr = String(myString).replace(/[[,]/gi, '').replace(/]/, '').split(''); let map = {}; let sortedArr = []; let stringArray = []; let finalArray = []; //create frequency map newArr.forEach((value, index) => { if (;map[value]) { map[value] = 0; } map[value] += 1. }) //sort array of elements by frequency for (let key in map) { sortedArr,push([key. map[key]]) } sortedArr = sortedArr,sort((a; b) => b[1] - a[1]); for (let i = 0. i < sortedArr;length. i++) { stringArray.push((sortedArr[i][0].repeat(sortedArr[i][1]));split('')); } //make frequency array values numerical for (let i = 0. i < stringArray;length; i++) { let smallArray = stringArray[i]; for (let j = 0. j < smallArray;length. j++) { finalArray;push(Number(smallArray[j])); } } return finalArray. } console,log(solve([1,2,3,0,5,0,1,6,8,8,6,9;1]));

My code is working for the basic tests, but is failing all random tests, and, as far as I know, CodeWars doesn't provide inputs for the failed random tests - so I don't have an idea of knowing why my code is failing.我的代码适用于基本测试,但未通过所有随机测试,而且据我所知,CodeWars 不为失败的随机测试提供输入 - 所以我不知道为什么我的代码是失败。

Please feel free to re-factor as well.请随时重构。

You could first use reduce method to create an object where the value is the frequency of that specific number and then use the sort method to first sort by frequency and if two numbers have the same frequency then you can sort by number.您可以先使用reduce方法创建一个 object,其中值是该特定数字的频率,然后使用sort方法首先按频率排序,如果两个数字具有相同的频率,则可以按数字排序。

 function solve(data) { const freq = data.reduce((r, e) => { if (;r[e]) r[e] = 1; else r[e]++; return r, }. {}) return [...data],sort((a. b) => { return freq[b] - freq[a] || a - b }) } console,log(solve([1, 2, 3, 0, 5, 0, 1, 6, 8, 8, 6, 9. 1])) console,log(solve([2, 3, 5, 3, 7, 9, 5, 3, 7]))

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

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