Ordering div elements based on properties of associated objects inside an array
I have an array of objects box[]
, and a div
element for each of these objects with class .box
. Each object has a numeric property box[].id
, which is used to identify the corresponding div
element which has the same id
attribute. I want to create a function to order the div
elements based on other properties of their related objects, I think it would be something like this using JavaScript and jQuery:
// Call my order function based on property1 for example.
sortBox("property1");
function sortBox(property) {
var order;
$(".box").each(function (i) {
// Gets the property on which to sort for each div
order = box[this.id][property];
//////////////////////
//.......????.......//
//////////////////////
});
}
This gets the property for each div
to do the sorting but 开发者_如何转开发I have no idea what to do after to order the divs based on that property and update the Html. Please help, what is the proper way to do this? Any ideas, examples, suggestions? Thanks in advance.
You should look into the sort()
-function, e.g.:
var boxes = $(".box");
// convert boxes to a regular array
boxes.sort(sortFunc);
function sortFunc(div1, div2) {
// please note that the result is in descending order (see below)
// if div1 > div2 return -1
// if div1 < div2 return 1
// if div1 == div2 return 0
}
Then you can run a loop to insert each DIV
as the first element before the first child of the parent
boxes.each(
function(el) {
el.parentNode.insertBefore(el, el.parentNode.firstChild);
});
Because the boxes
are sorted descending you end up with the "smallest" element in the first position.
This might contain syntax errors!
I would go the other direction.
- Convert
box
to an array. - Use the built in
array.sort
- clear the container and append the elements in order from sorted array.
var boxArray = []; for (var b in box) boxArray.push({id: b, box: b}); boxArray = boxArray.sort(function (a, b) { if (a.box.prop1 < b.box.prop1) return -1; else if (a.box.prop1 > b.box.prop1) return 1; return 0; });
Box array is now sorted and you can clone/copy elements into a new container.
Ok, I came up with this:
// the prop param is the object property used to sort the array of objects.
function sortBox(prop) {
box.sort(function (a, b) {
if (a[prop] < b[prop]) {
return -1;
} else if (a[prop] > b[prop]) {
return 1;
}
return 0;
});
}
Then I can call my sortBox
function to sort my box[]
array based on any of the properties of its objects. Then I delete the existing <div>
elements with jQuery empty() and create them again with the array sorted:
$("#boxcontainer").empty();
// the html property specifies the <div> html
for (var i = 0, len = box.length; i < len; i++) {
$("#boxcontainer").append(box[i].html);
}
精彩评论