views:

36

answers:

1

How can I take this code

<script>
var arr = [<%= myArray %>+<%= my2Array %>]; 
var sorted_arr = arr.sort(); 
var results = []; 
for (var i = 0; i < arr.length - 1; i += 1) { 
        if (sorted_arr[i + 1] == sorted_arr[i]) { 
                results.push(sorted_arr[i]); 
        } 
} 
 document.write(results +"<br />");
</script>

and convert it to <% the above script %> and keep the functionality?

Why does the script work in the script tag but not when I place it in <% %>

    <%
var arr = [myArray+my2Array]; 
var sorted_arr = arr.sort(); 
var results = []; 
for (var i = 0; i < arr.length - 1; i += 1) { 
        if (sorted_arr[i + 1] == sorted_arr[i]) { 
                results.push(sorted_arr[i]); 
        } 
} 
%>
<%= results %>

If I use it like this the results are returned as empty

I suspect the reason why it is not working is because the results value is not getting populates... In the script version it gets the time to populate and loop

+1  A: 

If you want to run your code server side you need to change the line

var arr = [myArray+my2Array]; 

to

var arr = (myArray+','+my2Array).split(',');
meouw
var arr = (myArray+my2Array).split(','); var sorted_arr = arr.sort();var results = [];for (var i = 0; i < arr.length - 1; i += 1) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } Works 100% thanks meouw!
Gerald Ferreira