JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
You can write:
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
http://www.w3schools.com/js/js_loop_for.asp
ARRAY MAP
Return an array with the square root of all the values in the original array:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
The result will be:
2,3,4,5
http://www.w3schools.com/jsref/jsref_map.asp
YOUR EXAMPLE
var order = [3, 2, 4, 1]; //Map Order
var el = $('#sort'); //Get ID of target control
var map = {}; //Create empty map
$('#sort div').each(function() { //For each control of ID ...
var el = $(this); //Set el as input id ...
map[el.attr('n')] = el; //add an attribute called n to each matching control
});
for (var i = 0, l = order.length; i < l; i ++) { //loop through array up to the length of array
if (map[order[i]]) { //If map equals current iteration
el.append(map[order[i]]); //Apply order
}
}
FLEXBOX
On a side note the effect you are trying to achieve can be quite easy to achieve if you are willing to use the css3 flex-box which has sorting functionality.
http://www.w3schools.com/cssref/css3_pr_order.asp