For this CodeWars challenge, the idea is to sort the array by frequency of elements - from most occurring to least occurring. 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.
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.
Please feel free to re-factor as well.
[21, 22]will become[2,1,2,2].let newArr = arr.map(e => e.toString())