Solved

javascript re order an array based on a contained arrays value

Posted on 2014-02-11
10
183 Views
Last Modified: 2014-02-12
data = "val1;val2;val3;val4;val5;val6;val7;val8;val9,val1;val2;val3;val4;val5;val6;val7;val8;val9,val1;val2;val3;val4;val5;val6;val7;val8;val9;val1;val2;val3;val4;val5;val6;val7;val8;val9"

arrData = data.split(",")

arrData = reorder(arrData,7)

How can I re-order arrData so that the array is ordered by val8, the 8th value in the string?
0
Comment
Question by:KeithMcElroy
10 Comments
 
LVL 19

Expert Comment

by:Rikin Shah
ID: 39852346
Hi,

arrData.sort(); will do the work.
0
 

Author Comment

by:KeithMcElroy
ID: 39852352
Actually, the 8th and then the 2nd  elements
0
 

Author Comment

by:KeithMcElroy
ID: 39852359
How do I get it to sort based on the 8th then the 2nd value of the semicolon parsed string within each array element?
0
 

Author Comment

by:KeithMcElroy
ID: 39852364
There are two delimiters, first a "," for the array, then semi-colon for each element within each array element.
0
 
LVL 14

Expert Comment

by:Pierre Cornelius
ID: 39852543
I put together an example showing what you want. It displays the array in a table and if you click on the table headings, it will do the sort.
<!DOCTYPE HTML>
<html>
<head></head>
<body>

	<div id="example"></div>
	
	<script type="text/javascript">
	
	var data="apple;fruit;4,banana;fruit;2,peas;vegetables;8,carrots;vegetables;3";

	var arrData = data.split(',');
	var numRows = arrData.length;
	for (i in arrData)
	{
		arrData[i] = arrData[i].split(';');
	}
	var numCols = arrData[0].length;

	//put in table to illustrate
	function arrDataToTable()
	{
		var htmRows='';
		for (var row=0; row<numRows; row++)
		{
		  htmRows+='<tr>';	
		  for (var col=0; col<numCols; col++)
		  {
			htmRows+='<td>'+arrData[row][col]+'</td>'
		  }
		  htmRows+='</tr>';	
		}

		document.getElementById('example').innerHTML='<table border="1" style="border-collapse:collapse;"><thead><tr><th>Item</th><th>Type</th><th>Qty</th></tr></thead><tbody>'+htmRows+'</tbody></table>';
		
		//add heading click events
		var headings = document.getElementsByTagName("th"); 

		for (var i = 0; i < headings.length; i++ ) 
		{    
			headings[i].addEventListener("click", function() 
				{ 
				SortByCol(this.cellIndex); 
				}
				, false
				); 
		} 		
	}
	
	//sort function
	function SortByCol(col)
	{
		arrData.sort(function(a,b)
			{			
				//number sort for 3rd col
				if (col===2)
				{
					return (parseInt(a[col])===parseInt(b[col]))?0:(parseInt(a[col])>parseInt(b[col]))?1:-1;
				}
				else
				{
					//sort as text
					return (a[col]===b[col])?0:(a[col]>b[col])?1:-1;
				}
			}
		);
		arrDataToTable();
	}
	
	//create table using arrData to illustrate
	arrDataToTable();
	
	
	
	</script>

</body>
</html>

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 9

Expert Comment

by:Sar1973
ID: 39852853
Are you looking for a code that reorders the elements by shifting the val8 at first position?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39852981
Test page : http://jsfiddle.net/6A8Bb/2/

var strData = "val1;val2;val3;val4;val5;val6;val7;val8;val9,val1;val2;val3;val4;val5;val6;val7;val8;val9,val1;val2;val3;val4;val5;val6;val7;val8;val9;val1;val2;val3;val4;val5;val6;val7;val8;val9"

var reorder = function(str) {
    var arrData = str.split(",");
    for(var i=0;i<arrData.length;i++) {
        var arr = arrData[i].split(";");
        arr = arr.sort(function(a, b) {
            return (a>b)?1:-1;
        });
        arrData[i] = arr.join(";");
    }
    return arrData.join(",");
}

strData = reorder(strData);

// CHECKING
alert(strData);

Open in new window

0
 

Author Comment

by:KeithMcElroy
ID: 39853201
I think this is close:  I modified the val8 to be 'out of order'.
the returned array would resort the semicolon delimited array into val8a,val8b,val8c.



var strData = "val1;val2;val3;val4;val5;val6;val7;val8b;val9,val1;val2;val3;val4;val5;val6;val7;val8c;val9,val1;val2;val3;val4;val5;val6;val7;val8;val9;val1;val2;val3;val4;val5;val6;val7;val8a;val9"
0
 

Author Comment

by:KeithMcElroy
ID: 39853209
The array would stay in it's original state of val1;val2,etc. in other words val8 would not move to the beginning.
0
 
LVL 9

Accepted Solution

by:
Sar1973 earned 500 total points
ID: 39853379
I think then that you need a function with a loop that replaces val8 with val8a, val8b, etc. with the fromCharCode function (see http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes for the codes).
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now