简体   繁体   中英

Ordering a Multi-Dimensional Array with Letters and Numbers

My school has asked me to develop a web app that can record homework, show timetables, etc. I use localStorage objects to store each homework, and then they are retrieved and put into a multi-dimensional array.

I have an Array that looks like this: (Placeholders for title, etc. used!)

1hvfkjdvhjh463574hdv
   0 : history
   1 : title
   2 : description
   3 : setdate
   4 : duedate
   5 : importance

1hft6ry4uyguy
   0 : art
   1 : title
   2 : description
   3 : setdate
   4 : duedate
   5 : importance

1ehfhhrewvfbjvds63
   0 : geography
   1 : title
   2 : description
   3 : setdate
   4 : duedate
   5 : importance

The 1 followed by random characters represents the category of the localStorage object (1 for homework - as oppose to timetable, etc.) and a unique 'id' for the homework.

Everything works fine apart from sorting/ordering the array.

The below method does not seem to work:

homework.sort(function(a, b) {
    if (a[0] < b[0]) return  1;
    if (a[0] > b[0]) return -1;
    return 0;
});

for(var x in homework) {
    document.write(homework[x] + "<br />");
}

The desired effect is that in the for loop, the array is ordered by the lesson, Art, History, Geography...

In your comment you said

var i = 0, oJson = {}, sKey;
homework = new Array();
for (;sKey = window.localStorage.key(i); i++) {
    oJson[sKey] = JSON.parse(window.localStorage.getItem(sKey));
    if(sKey.substring(0,1) === "1") { homework[sKey] = oJson[sKey]; }
}

Using homework[sKey] means you are adding properties to the Array as if it's an Object, not adding new items to your Array like it's a list. You can't sort these properties.

Try creating homework to have items in the form [sKey, oJson[sKey]] instead.

var i = 0, oJson = {}, sKey,
    homework = [];                             // Array literal
while (sKey = window.localStorage.key(i++)) {  // same loop using while
    oJson[sKey] = JSON.parse(window.localStorage.getItem(sKey));
    if(sKey.charAt(0) === "1")                 // test first char
        homework.push([sKey, oJson[sKey]]);    // Using `homework` as Array
}

Now when you sort your array items, you'll want to sort by the first index, just as you were trying to before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM