js - sort
reoder array
by Alejandro M
HTML
<div id="test">Items:</div>
JavaScript
var items = [
{ "id": 3, "name": "a", "test":"asd"},
{ "id": 3, "name": "c","test":"asd" },
{ "id": 3, "name": "b","test":"asd" },
{ "id": 1, "name": "b" ,"test":"asd"},
{ "id": 10, "name": "a","test":"asd" },
];
items.sort(function(a,b) {
// return (a.id - b.id); //to avoid unicode order
return (a.id - b.id) || a.name.localeCompare(b.name); //second parameter to duplicate value
//localeCompare compare one string against the second variable..// -2 or -1 (or some other negative value) 0 if equal
//"a".localeCompare("b"); --> -1
//"b".localeCompare("a"); --> 1
//"a".localeCompare("a"); --> 0
});
console.log(items);
for (var i =0; i<items.length ; i++) {
console.log("s")
var div = document.getElementById('test');
var child = document.createElement('div');
child.innerHTML = '<p>'+ items[i].id +'-'+ items[i].name +'</p>';
child = child.firstChild;
document.getElementById('test').appendChild(child);
}