phppup Posted June 8, 2014 Share Posted June 8, 2014 I initially set up a few VAR items to learn some JS coding. Then it became apparent that altering the group and entering them into an array would be more effective. However, my limited knowledge is confusing the situation. Is there a simple comparison (with proper code and formatting) that someone can provide? Example: student in the school info desired: name, age, hair color, eye color As separate VAR listings I cannot sort by age, so I create an array, but how can I name them student 1, 2, 3 etc. (or do I not want to??). Quote Link to comment https://forums.phpfreaks.com/topic/289069-javascript-array-versus-var/ Share on other sites More sharing options...
.josh Posted June 9, 2014 Share Posted June 9, 2014 There are a lot of ways to skin this cat, but ultimately it boils down to sorting multi-dimensional data. Now, this can take the form of a multi-dimension array, such as: var students = [ ['Joe',20], ['Jane',19], ['Bella',22] ]; But having each student represented as an object may be more useful to you in the long run, so here is an example of having an array of objects: // this is a custom function to sort by, which we will pass to the native Array.sort() method // first argument is the property name to sort by (e.g. 'age'). by default it sorts ascending // but you can pass true or any truthy value as 2nd arg to make it sort descending function sortBy (p,o) { if(!p)return; var o=(o)?-1:1; return function (a,b) { var r=(a[p]<b[p])?-1:(a[p]>b[p])?1:0; return r*o; } } // here is a simple Student "class" to make each student as an object. // since this is an example, it doesn't really do anything except for // set properties for the student (name, age, etc..) function Student (props) { for (var p in props) { this[p] = props[p]; } } // here is our top level array var students = []; // now lets put some student objects into the array students.push(new Student({'name':'Joe','age':'20','hairColor':'blonde','eyeColor':'black'})); students.push(new Student({'name':'Jane','age':'19','hairColor':'red','eyeColor':'green'})); students.push(new Student({'name':'Bella','age':'22','hairColor':'black','eyeColor':'gray'})); // here is an example of sorting by age: students.sort(sortBy('name')); // and to show that it has been sorted, loop through the students // and just dump the student object to the js console for (var i=0,l=students.length;i<l;i++) { console.log (students[i]); } /* js console will look something like this: Student { name="Jane", age="19", hairColor="red", more...} Student { name="Joe", age="20", hairColor="ginger", more...} Student { name="Bella", age="22", hairColor="black", more...} */ Quote Link to comment https://forums.phpfreaks.com/topic/289069-javascript-array-versus-var/#findComment-1482230 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.