Reputation: 2211
I am working on this code and need to sort the JSON output by a value, in this case called cars. How can I accomplish it in this code?
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "test.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
for (var i = 0; i <= lines.length; i++){
var obj = JSON.parse(lines[i]);
document.getElementById("demo").innerHTML += obj._serverMessages[0].car + " " + obj.creator.substr(2, obj.creator.length) + " / " + obj._serverMessages[0].content + "<br>";
}
}
}
}
txtFile.send(null);
Upvotes: 0
Views: 66
Reputation: 976
I think this code will give you the result you were looking for:
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "test.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) {
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
var array = [];
for (var i = 0; i <= lines.length; i++) {
array.push(JSON.parse(lines[i]))
}
array.sort(function(a, b){
if (a._serverMessages && a._serverMessages.length && a._serverMessages[0] && a._serverMessages[0].car) {
if (b._serverMessages && b._serverMessages.length && b._serverMessages[0] && b._serverMessages[0].car) {
return a._serverMessages[0].car > b._serverMessages[0].car? 1 : -1;
} else return -1;
} else return 1;
});
for (var i = 0; i <= array.length; i++) {
document.getElementById("demo").innerHTML += array[i]._serverMessages[0].car + " " + array[i].creator.substr(2, array[i].creator.length) + " / " + array[i]._serverMessages[0].content + "<br>";
}
}
}
}
txtFile.send(null);
Upvotes: 1