Click here to Skip to main content
15,563,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would need to erase the value if it exceeds the number of n, for example:
JavaScript
sortN([2, 3, 3, 3, 4, 4], 1);-> [2, 3, 4]

In other words, the number of occurrences should not exceed n. I have been trying tackle this problem with different approaches but still can`t get the desired output

What I have tried:

The closest I got was to count number of occurrences of every element, like this:
JavaScript
function compressArray(original) {
 
	var compressed = [];
	// make a copy of the input array
	var copy = original.slice(0);
 
	// first loop goes over every element
	for (var i = 0; i < original.length; i++) {
 
		var myCount = 0;	
		// loop over every element in the copy and see if it's the same
		for (var w = 0; w < copy.length; w++) {
			if (original[i] == copy[w]) {
				
				myCount++;
				
				delete copy[w];
			}
		}
 
		if (myCount > 0) {
		
			compressed.push(original[i], myCount);
		}
	}
 
	return compressed;
};

Is this really useful? Should I take a different approach?
Posted
Updated 10-Aug-16 4:51am

1 solution

How about something like this:
JavaScript
function compressArray(original, maxOccurrences) {
    if (!original) { return null; }
    if (maxOccurrences < 1) { return []; }
    
    var result = [];
    var itemCounts = {};
    for (var index = 0; index < original.length; index++){
        var item = original[index];
        var count = itemCounts[item] || 0;
        if (count < maxOccurrences) {
            result.push(item);
            itemCounts[item] = count + 1;
        }
    }
    
    return result;
}

Demo[^]
 
Share this answer
 
Comments
AlexLearne 10-Aug-16 11:05am    
Thank you a lot! But since I am a newbie I have some questions to ask.Would you please help me understand the code completely?
What is this line doing? var count = itemCounts[item] || 0;
Are you adding the values to the object?
Thanks anyway!
Richard Deeming 10-Aug-16 11:13am    
It's a shorthand way of writing:

var count = itemCounts[item];
if (count === undefined) {
   count = 0;
}


When we encounter an item we haven't seen before, the itemCounts object doesn't contain a value for that item, so itemCounts[item] returns undefined. In that case, we want count to be set to 0, since we haven't seen that item yet.

Within the if block, we then store count + 1 against the item in the itemCounts object. This will add a new value if the key doesn't exist yet, or update the existing value if it does exist.
AlexLearne 10-Aug-16 11:17am    
Thanks! Great help!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900