Solved

Fixing Array to be in order of most occurances and alphabetical

Posted on 2014-03-12
11
113 Views
Last Modified: 2014-03-13
Below you find code that I am using to group together values and find how many times it occured.  However, the format it is coming out is not what I would like.  

I am getting this:
John,Paul,Peter,2,4,2

I would like to get it like this:
Paul (4)
John (2)
Peter (2)

Basically in order of most occurnaces and then alphabetical if possible with the number or occurances in ().  

foo(["John","Paul","Peter","Peter","Paul","Paul","Paul","John"])

function foo(arr) {
    var a = [], b = [], prev;

    arr.sort();
    for ( var i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }
	//return a + "(" + b + );
    return [a, b];
}

Open in new window

0
Comment
Question by:flfmmqp
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
11 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39924448
var testArray = new Array("John","Paul","Peter","Peter","Paul","Paul","Paul","John")
testArray.sort()
var newArray = compressArray(testArray);

console.log(newArray)
function compressArray(original) {
    var sorted = [];
    current=""
    count=1
	for (var i = 0; i < original.length; i++) {
         if(current==original[i]){
            count++
        }       
        
        if((current!=original[i]&&current!="")||i==original.length-1){
			var a = new Object();
			a.value = original[i-1];
			a.count = count;
			sorted.push(a);
            count=1
        }
        current=original[i]
 	}
sorted.sort(function(a,b) {
    return  a.count-b.count;
});
	return sorted;
};

Open in new window

0
 

Author Comment

by:flfmmqp
ID: 39924497
I'm pretty new to Javascript.  How should I call this?  I've tried a few different approaches but am getting undefined errors.  I thought this would work.  

I am using this in a html page using IE9 if that makes a differences.  Do I need anything special in my script to use the Console.log  piece?

foo(["John","Paul","Peter","Peter","Paul","Paul","Paul","John"])


function foo(testArray) {
//var testArray = new Array("John","Paul","Peter","Peter","Paul","Paul","Paul","John")
		testArray.sort()
		var newArray = compressArray(testArray);
		
		console.log(newArray)
		function compressArray(original) {
			var sorted = [];
			current=""
			count=1
			for (var i = 0; i < original.length; i++) {
				 if(current==original[i]){
					count++
				}       
				
				if((current!=original[i]&&current!="")||i==original.length-1){
					var a = new Object();
					a.value = original[i-1];
					a.count = count;
					sorted.push(a);
					count=1
				}
				current=original[i]
			}
		sorted.sort(function(a,b) {
			return  a.count-b.count;
		});
			return sorted;
		}; 
}

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
ID: 39924514
Why are you nesting the functions?  Just use the code I posted.

In Developer Tools (F12) you should see the Console tab (cannot remember the layout).
The console.log is just there for testing so you can see the returned array, it can be removed
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:flfmmqp
ID: 39924526
I need to call it though.  I am grabbing the values from another spot.  They will not be hard coded
0
 

Author Comment

by:flfmmqp
ID: 39924537
I'm not getting any values.  Just this:

[object Object],[object Object],[object Object],[object Object]

Even using this - var testArray = new Array("John","Paul","Peter","Peter","Paul","Paul","Paul","John")
0
 
LVL 58

Expert Comment

by:Gary
ID: 39924541
Call what
All you need to do is pass the array to the function

var testArray = ["John","Paul","Peter","Peter","Paul","Paul","Paul","John"]
testArray.sort()

var newArray = compressArray(testArray);
...
...

Open in new window


http://jsfiddle.net/GaryC123/rfW6x/3/
0
 

Author Comment

by:flfmmqp
ID: 39924555
A little more info:

        function selectInBuffer(response){
          var feature;
          var features = response.features;
          var inBuffer = [];
          //filter out features that are not actually in buffer, since we got all points in the buffer's bounding box
          for (var i = 0; i < features.length; i++) {
            feature = features[i];
            if(circle.contains(feature.geometry)){
              inBuffer.push(feature.attributes[featureLayer.objectIdField]);
            }
          }
          var query = new Query();
          query.objectIds = inBuffer;
          //use a fast objectIds selection query (should not need to go to the server)
          featureLayer.selectFeatures(query, FeatureLayer.SELECTION_NEW, function(results){
            var r = "";
            r = "5 Mile Aggregate Browser:" +"<br> Retailer Summary: " + GetUnique(results) + "<BR> Unigue arrary: " + [b]compressArray(testArray[/b]);
            dom.byId("messages").innerHTML = r;
          });
        }


		var testArray = new Array("John","Paul","Peter","Peter","Paul","Paul","Paul","John")
		testArray.sort()
		var newArray = compressArray(testArray);
		
		//console.log(newArray)
		function compressArray(original) {
			var sorted = [];
			current=""
			count=1
			for (var i = 0; i < original.length; i++) {
				 if(current==original[i]){
					count++
				}       
				
				if((current!=original[i]&&current!="")||i==original.length-1){
					var a = new Object();
					a.value = original[i-1];
					a.count = count;
					sorted.push(a);
					count=1
				}
				current=original[i]
			}
		sorted.sort(function(a,b) {
			return  a.count-b.count;
		});
			return sorted;
		}; 

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
ID: 39924567
What is that supposed to mean to me?
0
 

Author Comment

by:flfmmqp
ID: 39924570
BTW this is not coming out how I was hoping.  That alert box is not coming out like this order or looking like this:

I would like to get it like this:
Paul (4)
John (2)
Peter (2)


Thanks for trying to help.  But currently the result does not look much different then what I already have posted code for.
0
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
ID: 39924589
0
 

Author Closing Comment

by:flfmmqp
ID: 39926031
I'm awarding the points as I think you answered my question here for me.  However, I'm not completely done with this project.  So if you would like to take a crack at my last issue with that here is the link to my next question.   Thanks for all of your help.
 
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28387540.html
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Geolocation works...sometimes 2 35
jquery change div image on page reload using Jquery 9 54
Difference between Highcharts and Mapbox 10 43
Javascript Error 10 21
Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question