MV Sort skills chronologically

Hello,
It's been many days I search a way to sort skills in the order where they was learn. I found plugin to sort them in different way except as I want.

I have too few notion in javascript and there is a limit at what I can do.

Thanks to the code of STORMTiger I found a way to sort as I need but for item. And I'm wonder if it's possible to adapt his code for skills?

Thanks a lot in advance!

This is a very old thread, and I don't know if for @_Soysauce_ this is still relevant, but while I was just searching to a solution of sorting items by myself, I landet here.

Reading all your answers and suggestions, I believe the answer was already here - or at least you were all close to it.

So I managed to do that task with very few lines of code and I would like to share this. I would like to hear if I have forgotten something at last?

My addition to this task is to just add one property to the "item" objects:
item._lastGainedDate which is set exactly in the function mentioned by @Maliki79 and set it to "Date()".

Hit me, but I believe this is the only function that covers all the possibilities that @Andar was concerned about. (I tried it and even if you stripp off a weapon that had been on the actor at game start, this function is called to put it to the menu!).

So the code is looking like that:
JavaScript:
former_Game_Party_gainItem = Game_Party.prototype.gainItem;
Game_Party.prototype.gainItem = function(item, amount, includeEquip) {
    // only when gaining item not by loosing
    if (amount > 0) {
        if (item) {
            if (!item._lastGainedDate) {
                item._firstGainedDate = Date();
            }
            item._lastGainedDate = Date();
        }  
    }


    former_Game_Party_gainItem.call(this, item, amount, includeEquip);
};


The function to sort by last acquired Item would look like this:
JavaScript:
//sort Items by last gained Date (last will be first)
Window_ItemList.prototype.makeItemList = function() {
    this._data = $gameParty.allItems().filter(item => this.includes(item));

    this._data.sort(function(a,b){
        if(a._lastGainedDate < b._lastGainedDate) return 1;
        if(a._lastGainedDate > b._lastGainedDate) return -1;
        return 0;
    });

    if (this.includes(null)) {
        this._data.push(null);
    }
};

I put everything in a plugin and it works quite decent!

(You may have noticed that I added another timestamp called item._firstGainedDate, so you could also sort by first acquisition of this item type)

So for me the answer is to note everything to the item id and to not try to think about single item "instances". That gives a simple solution that should also be fast in excecution.

Please comment, if you still see any issues.

My question would be how to make it possible to the user to choose a sorting option from the menu itself (how to add a kind of sorting option subwindow). If anybody has an idea on that, I'd be glad to hear about it 🙂
I couldn't find it in his thread, but @ATT_Turan has a plugin that let's you sort the skill order with a notetag, so you'd just give them the number in which order they are learned.
The notetag will just sort them in a definite order. I want to use skill as a way to record event chronologically so it's necessary they was not sort in a definite order.
Hmm, I don't think item timestamps can be saved.
Because the item parameter pulls data from $dataItems, which is loaded from a JSON file in data folder.
So every time you load a saved game, you lose the timestamps.
The correct way to do that is to save the timestamp somewhere inside $gameParty.


JavaScript:
(function(){
var gp_gainItem = Game_Party.prototype.gainItem;
Game_Party.prototype.gainItem = function(item, amount, includeEquip) {
    if (item && amount > 0) {
        this._itemOrderGain = this._itemOrderGain||[0];
        this._itemOrderGain[item.id]=Math.max(...this._itemOrderGain.filter(function(a){return !isNaN(a);}))+1;
    }

    gp_gainItem.call(this, item, amount, includeEquip);
};
})();

Game_Party.prototype.allItems = function() {
    return this.items().concat(this.equipItems()).sort((function(a,b){
      if(this._itemOrderGain){
        var aa=(this._itemOrderGain[a.id]||0) + a.id/100000;
        var bb=(this._itemOrderGain[b.id]||0) + b.id/100000;
        return bb-aa;
      }
      return a.id-b.id;
    }).bind(this));
};

(function(){
var ga_learnSkill=Game_Actor.prototype.learnSkill;
Game_Actor.prototype.learnSkill = function(skillId) {
    
    if (!this.isLearnedSkill(skillId)) {
        this._skills.splice(0,0,skillId);
        
        //this._skills.sort(function(a, b) {
        //    return a - b;
        //});
    }
};
})();
nope it doesn't work, skills are still sort as in the index.
And for item you're wrong, the game remember the order when item are collected. For skill it must be the same, example in "Karryn's prison", skill are ordered from the latest learn to the older, and the save game keep the sort.
Then you may have other plugin changing that part of code. I tried it on a fresh project and it worked.
Even in a new project with just your plugin it doesn't work 🙁
How did you test it?
I just create a new project, put your code in a new js file, then I create events which give me skill and finally I check how they are sort.

I just to see it, and it's specify in the topic but it's for MV.
Yea, by default items and skills are all sorted ascending by database ID.

I did a quick test and the code posted by @utunnels seems to work for me.
  1. Did you remember to import the plugin through the Plugin Manager?
  2. Did you remember to save your project to apply Plugin Manager changes before testing?
  3. Press F8 or F12 to open the dev tools window: do you see any error messages on its Console tab?
Here's an alternative that also works for me:
Spoiler: plugin code
JavaScript:
/*:
 * @target MV
 * @plugindesc Items/Skills are now retrieved from most to least recent acquisition.
 * @author Caethyril
 * @url https://forums.rpgmakerweb.com/threads/170842/
 * @help Free to use and/or modify for any project, no credit required.
 */
// Might also work as-is in MZ; I haven't tested it.
;void (function() {
'use strict';

    /** Iff `true`, apply item timestamps & sorting. */
    const APPLY_ITEMS = true;

    /** Iff `true`, apply skill timestamps & sorting. */
    const APPLY_SKILLS = true;

    /**
     * Identifier for new timestamp storage property on:
     * - `Game_Party` (items); and/or
     * - `Game_Actor` (skills).
     */
    const PROP = "_recent";

    // Skip if everything's disabled... O_o
    if (!APPLY_ITEMS && !APPLY_SKILLS)
        return;

    /**
     * `Array#sort` delegate function for items & skills.
     * @param {number} a
     * Timestamp for acquisition of item/skill.
     * @param {number} b
     * Timestamp for acquisition of item/skill.
     * @returns {number}
     * Indicates sort action.
     */
    const f = function(a, b) {
        return b - a;   // descending
    };

    // Recent item sorting.
    void (function() { if (!APPLY_ITEMS) return;

        /**
         * Sub-property getter for storing all timestamps on 1 object.
         * (To reduce scope pollution.)
         * @this {Game_Party}
         * Party instance.
         * @param {$dataWeapon|$dataArmor|$dataItem} item
         * Database item reference.
         * @returns {string|null}
         * Sub-property identifier, or `null` if container unrecognised.
         */
        const subProp = function(item) {
            switch (this.itemContainer(item)) {
                case this._weapons:
                    return "w";
                case this._armors:
                    return "a";
                case this._items:
                    return "i";
                default:
                    return null;
            }
        };

        /**
         * `Array#sort` function for weapons, armors, and items.
         * @this {Game_Party}
         * Party instance.
         * @param {$dataWeapon|$dataArmor|$dataItem} a
         * Database item reference.
         * @param {$dataWeapon|$dataArmor|$dataItem} b
         * Database item reference.
         * @returns {number}
         * Indicates sort action.
         */
        const fSort = function(a, b) {
            const pA = subProp.call(this, a);
            if (!pA)
                return 0;
            const pB = subProp.call(this, b);
            if (!pB)
                return 0;
            const tA = this[PROP][pA][a.id];
            if (!(tA > 0))  // implicit type-check
                return 0;
            const tB = this[PROP][pB][b.id];
            if (!(tB > 0))
                return 0;
            return f(tA, tB);
        };

        // Patch - initialise weapon/armor/item timestamp storage.
        void (function(alias) {
            Game_Party.prototype.initAllItems = function() {
                alias.apply(this, arguments);
                const o = this[PROP] = {};
                o.w = {}, o.a = {}, o.i = {};
            };
        })(Game_Party.prototype.initAllItems);

        // Patch - record timestamp when an item is gained.
        void (function(alias) {
            Game_Party.prototype.gainItem = function(item, count, includeEquip) {
                alias.apply(this, arguments);
                if (count > 0) {
                    const p = subProp.call(this, item);
                    if (p)
                        this[PROP][p][item.id] = Graphics.frameCount
                }
            };
        })(Game_Party.prototype.gainItem);

        // Patch - sort retrieved weapon, armor, item object lists.
        for (const m of ["weapons", "armors", "items"])
            void (function(alias) {
                Game_Party.prototype[m] = function() {
                    return alias.apply(this, arguments).sort(fSort.bind(this))
                };
            })(Game_Party.prototype[m]);

    })();

    // Recent skill sorting.
    void (function() { if (!APPLY_SKILLS) return;

        /**
         * `Array#sort` function for skills.
         * @param {number} a
         * Skill ID.
         * @param {number} b
         * Skill ID.
         * @returns {number}
         * Indicates sort action.
         */
        const fSort = function(a, b) {
            const tA = this[PROP].s[a];
            if (!tA)
                return 0;
            const tB = this[PROP].s[b];
            if (!tB)
                return 0;
            return f(tA, tB);
        };

        // Patch - initialise skill timestamp storage.
        void (function(alias) {
            Game_Actor.prototype.initSkills = function() {
                (this[PROP] = {}).s = {};
                alias.apply(this, arguments);
            };
        })(Game_Actor.prototype.initSkills);

        // Patch - record timestamp when a skill is learned.
        void (function(alias) {
            Game_Actor.prototype.learnSkill = function(skillId) {
                alias.apply(this, arguments);   // for compatibility
                this[PROP].s[skillId] = Graphics.frameCount;
                this._skills.sort(fSort.bind(this));
            };
        })(Game_Actor.prototype.learnSkill);

    })();

})();
// End of file.
Like @utunnels's approach, mine only applies to learned skills; skills added by an Add Skill trait will be unaffected.
Yea, by default items and skills are all sorted ascending by database ID.

I did a quick test and the code posted by @utunnels seems to work for me.
  1. Did you remember to import the plugin through the Plugin Manager?
  2. Did you remember to save your project to apply Plugin Manager changes before testing?
  3. Press F8 or F12 to open the dev tools window: do you see any error messages on its Console tab?
Here's an alternative that also works for me:
Spoiler: plugin code
JavaScript:
/*:
 * @target MV
 * @plugindesc Items/Skills are now retrieved from most to least recent acquisition.
 * @author Caethyril
 * @url https://forums.rpgmakerweb.com/threads/170842/
 * @help Free to use and/or modify for any project, no credit required.
 */
// Might also work as-is in MZ; I haven't tested it.
;void (function() {
'use strict';

    /** Iff `true`, apply item timestamps & sorting. */
    const APPLY_ITEMS = true;

    /** Iff `true`, apply skill timestamps & sorting. */
    const APPLY_SKILLS = true;

    /**
     * Identifier for new timestamp storage property on:
     * - `Game_Party` (items); and/or
     * - `Game_Actor` (skills).
     */
    const PROP = "_recent";

    // Skip if everything's disabled... O_o
    if (!APPLY_ITEMS && !APPLY_SKILLS)
        return;

    /**
     * `Array#sort` delegate function for items & skills.
     * @param {number} a
     * Timestamp for acquisition of item/skill.
     * @param {number} b
     * Timestamp for acquisition of item/skill.
     * @returns {number}
     * Indicates sort action.
     */
    const f = function(a, b) {
        return b - a;   // descending
    };

    // Recent item sorting.
    void (function() { if (!APPLY_ITEMS) return;

        /**
         * Sub-property getter for storing all timestamps on 1 object.
         * (To reduce scope pollution.)
         * @this {Game_Party}
         * Party instance.
         * @param {$dataWeapon|$dataArmor|$dataItem} item
         * Database item reference.
         * @returns {string|null}
         * Sub-property identifier, or `null` if container unrecognised.
         */
        const subProp = function(item) {
            switch (this.itemContainer(item)) {
                case this._weapons:
                    return "w";
                case this._armors:
                    return "a";
                case this._items:
                    return "i";
                default:
                    return null;
            }
        };

        /**
         * `Array#sort` function for weapons, armors, and items.
         * @this {Game_Party}
         * Party instance.
         * @param {$dataWeapon|$dataArmor|$dataItem} a
         * Database item reference.
         * @param {$dataWeapon|$dataArmor|$dataItem} b
         * Database item reference.
         * @returns {number}
         * Indicates sort action.
         */
        const fSort = function(a, b) {
            const pA = subProp.call(this, a);
            if (!pA)
                return 0;
            const pB = subProp.call(this, b);
            if (!pB)
                return 0;
            const tA = this[PROP][pA][a.id];
            if (!(tA > 0))  // implicit type-check
                return 0;
            const tB = this[PROP][pB][b.id];
            if (!(tB > 0))
                return 0;
            return f(tA, tB);
        };

        // Patch - initialise weapon/armor/item timestamp storage.
        void (function(alias) {
            Game_Party.prototype.initAllItems = function() {
                alias.apply(this, arguments);
                const o = this[PROP] = {};
                o.w = {}, o.a = {}, o.i = {};
            };
        })(Game_Party.prototype.initAllItems);

        // Patch - record timestamp when an item is gained.
        void (function(alias) {
            Game_Party.prototype.gainItem = function(item, count, includeEquip) {
                alias.apply(this, arguments);
                if (count > 0) {
                    const p = subProp.call(this, item);
                    if (p)
                        this[PROP][p][item.id] = Graphics.frameCount
                }
            };
        })(Game_Party.prototype.gainItem);

        // Patch - sort retrieved weapon, armor, item object lists.
        for (const m of ["weapons", "armors", "items"])
            void (function(alias) {
                Game_Party.prototype[m] = function() {
                    return alias.apply(this, arguments).sort(fSort.bind(this))
                };
            })(Game_Party.prototype[m]);

    })();

    // Recent skill sorting.
    void (function() { if (!APPLY_SKILLS) return;

        /**
         * `Array#sort` function for skills.
         * @param {number} a
         * Skill ID.
         * @param {number} b
         * Skill ID.
         * @returns {number}
         * Indicates sort action.
         */
        const fSort = function(a, b) {
            const tA = this[PROP].s[a];
            if (!tA)
                return 0;
            const tB = this[PROP].s[b];
            if (!tB)
                return 0;
            return f(tA, tB);
        };

        // Patch - initialise skill timestamp storage.
        void (function(alias) {
            Game_Actor.prototype.initSkills = function() {
                (this[PROP] = {}).s = {};
                alias.apply(this, arguments);
            };
        })(Game_Actor.prototype.initSkills);

        // Patch - record timestamp when a skill is learned.
        void (function(alias) {
            Game_Actor.prototype.learnSkill = function(skillId) {
                alias.apply(this, arguments);   // for compatibility
                this[PROP].s[skillId] = Graphics.frameCount;
                this._skills.sort(fSort.bind(this));
            };
        })(Game_Actor.prototype.learnSkill);

    })();

})();
// End of file.
Like @utunnels's approach, mine only applies to learned skills; skills added by an Add Skill trait will be unaffected.

Yes it's work perfectly, now it must sort to the first to the last.

Anyway thanks a lot !!!
how about pulling (and ordering accordingly to) the IDs from an array?
instead of "learn this ID from the database", order a "learn the last entry from this array", which itself is an ID, that you push into the array, to be pulled from the database.
I'm rusty in matters coding, but that's basically the gist of it: put an array on the mid of it all.
you can straight or reverse the array as you want, with one command... the call to pull *from* it, would be unchanged.
now it must sort to the first to the last
Spoiler: with my code
This function determines the sort order:
JavaScript:
    const f = function(a, b) {
        return b - a;   // descending
    };
To sort ascending instead, that would be:
JavaScript:
    const f = function(a, b) {
        return a - b;   // ascending
    };
Spoiler: with utunnels's code
I think you could replace this line (skills):
JavaScript:
        this._skills.splice(0,0,skillId);
...with this:
JavaScript:
        this._skills.push(skillId);
And this line (items):
JavaScript:
        return bb-aa;
...with this:
JavaScript:
        return aa-bb;
(I've realised that my code doesn't actually sort mixed-category item lists completely. Technically that's not a problem without plugins, because by default item lists only ever have 1 category, e.g. items or weapons. The code suggested by @utunnels doesn't have this issue, because it changes allItems instead, and the core item list windows only ever reference that.)
@caethyril By the way, I didn't use frameCount because you can add multiple items at the same frame.
I don't know but for your both code there is no change.
For caethyril's code, skill are sort in the wrong order (from the last to the first).
And for utunnels's code, they are just sort like in the index.

But it's strange because I have nothing which interfere with yours codes.
Can you post some screenshots of yours?
1. Your items and skills setup.
2. The event that add items, skills.
3. The menus that show them.
It's with caethyril's code: they are sorted from the last to the first.
All items, skills have the same configuration.

EDIT:
OK it's work, it's just me who is stupid: caethyril's code was open/change in notepad but was not the same file I tested.
(T-T)

So again thanks a lot!!!
OK it's work, it's just me who is stupid: caethyril's code was open/change in notepad but was not the same file I tested.
I see! No worries, mistakes happen. Good to hear you got it working! 👋

Original thread: https://forums.rpgmakerweb.com/threads/sort-skills-chronologically.170842/