Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions 1636.sort-array-by-increasing-frequency.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/* URL of this problem
* https://leetcode.com/problems/sort-array-by-increasing-frequency/description/
*
* @param {number[]} nums
* @return {number[]}
*/

var frequencySort = function(nums) {
const UniqueNums = [...new Set(nums)];
const SortedNums = [];

// Make an array of each unique number and push the array to SortedNums
for (let i = 0; i < UniqueNums.length; i++) {
const CurrNums = nums.filter(num => num === UniqueNums[i]);

SortedNums.push(CurrNums);
}
SortedNums.sort((currNums, nextNums) => {
const CurrLen = currNums.length;
const NextLen = nextNums.length;
const CurrNum = currNums[0];
const NextNum = nextNums[0];

// Sort the arrays in a descending order by its number if the arrays have the same occurrence
if (CurrLen === NextLen) {
return NextNum - CurrNum;
}
// Sort the arrays in an ascending order by occurrence
return CurrLen - NextLen;
});

return SortedNums.flat();
};

module.exports = frequencySort;
14 changes: 14 additions & 0 deletions frequencySort.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const frequencySort = require("./1636.sort-array-by-increasing-frequency");

test("Return the array sorted by increasing frequency and decreasing value for the same frequency", () => {
expect(frequencySort([1,1,2,2,2,3])).toEqual([3,1,1,2,2,2]);
});

test("Return the array with negative values sorted by increasing frequency and decreasing value for the same frequency", () => {
expect(frequencySort([-1,1,-6,4,5,-6,1,4,1])).toEqual([5,-1,4,4,-6,-6,1,1,1]);
});

test("Return the array with Infinity and -Infinity sorted by increasing frequency and decreasing value for the same frequency", () => {
expect(frequencySort([1,1,1,-Infinity,-Infinity,Infinity,Infinity]))
.toEqual([Infinity,Infinity,-Infinity,-Infinity,1,1,1]);
});