I want to reorder the following list of movies in such a way that movies of the version==3D should be placed before the ones in version==2D.
Input
<films>
<film name="Foobar" version="2D"></film>
<film name="Foobar" version="3D"></film>
<film name="Foobaz" version="2D"></film>
<film name="Foobaz" version="3D"></film>
</films>
Desired Output
<films>
<film name="Foobar" version="3D"></film>
<film name="Foobar" version="2D"></film>
<film name="Foobaz" version="3D"></film>
<film name="Foobaz" version="2D"></film>
</films>
I've fiddled around and ended up with the following code. Hopefully it understandable.
/***
Extend Array prototype to have a indeOf function
***/
Array.prototype.indexOf = function(item) {
var index = 0, length = this.length;
for ( ; index < length; index++ ) {
if ( this[index] == item )
return index;
}
return -1;
};
var xmlString = '\
<films>\
<film name="Foobar" version="2D"></film>\
<film name="Foobar" version="3D"></film>\
<film name="Foobaz" version="2D"></film>\
<film name="Foobaz" version="3D"></film>\
</films>';
var xml = new XML(xmlString);
var sortVersion = ['2D', '3D'];
var uniqueMovies = new Array();
for (var index = 0; index < xml.elements().length(); index++) {
if (index == 0) continue;
// Fetch meta data of previous movie
var prevTitle = xml.elements()[index - 1].@name;
var prevVersion = xml.elements()[index - 1].@version;
var prevVersionIdx = sortVersion.indexOf(prevVersion);
// Fetch meta data of current movie
var curTitle = xml.elements()[index].@name;
var curVersion = xml.elements()[index].@version;
var curVersionIdx = sortVersion.indexOf(curVersion);
// If both movie title matches verify which movie should be prioritized
if (prevTitle == curTitle) {
if (prevVersionIdx < curVersionIdx) {
// Movie prio movie before less prio movie
xml.insertChildBefore(xml.elements()[index - 1], xml.elements()[index]);
// And delete the next in index
delete xml.elements()[index + 1];
}
}
}
$.writeln("-----");
$.writeln("");
$.writeln(xml.elements().toString());
return xml
However when I run this script I end with the following result where nothing is changed at all although the both if condition are hit and the element on index[1] is added before index[0].
<films>
<film name="Foobar" version="2D"/>
<film name="Foobar" version="3D"/>
<film name="Foobaz" version="2D"/>
<film name="Foobaz" version="3D"/>
</films>
Does anyone have an idea what I am doing wrong here?
if (prevTitle == curTitle)condition ? I also recommend that you edit your question to show your desired xml output. - RobC