1

So I am working on a Grid-based Tactical Battle System for RPG Maker MV (uses Javascript), and I am stuck on developing the turn order. My knowledge of what certain arrays are called is slim so I apologize in advance.

WHAT I AM DOING (simplified without the other classes):

var turnOrder = [];
var roll = (actor.agi - 10) + Math.randomInt(100);
var data = {
   id: actor._actorId,
   type: "player",
   init: roll
};
turnOrder.push(data);

And that loops throughout the party members, and then adds the enemy (by eventId) at the end.

WHAT I NEED HELP WITH: How would I sort the following example? (2 players + 1 enemy)

[{"id":1,"type":"player","init":27},
 {"id":2,"type":"player","init":4},
 {"id":1,"type":"enemy","init":17}]

How would I sort the above by "init" only? (in descending order) I appreciate anyone and everyone in advance for this (I couldn't seem to find it via other searches).

3
  • 2
    Arrays in javascript inherit the .sort method. I think that would likely come up first in your searches if "javascript" and "sort" were mentioned together. .......... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 12, 2020 at 22:52
  • Does this answer your question? Sorting array of objects by property Commented Jul 12, 2020 at 22:55
  • I take it back - the .sort and => syntax actually work... huh.. surprising. Welp! Thank you all, got it to work now :) <3 Commented Jul 12, 2020 at 23:23

2 Answers 2

1

You could use sort to sort based on init in descending order

pool=[{"id":1,"type":"player","init":27},
 {"id":2,"type":"player","init":4},
 {"id":1,"type":"enemy","init":17}]


  pool.sort((a,b)=>b.init-a.init)
  console.log(pool)

Sign up to request clarification or add additional context in comments.

1 Comment

Oh... all this time I thought "=>" wasn't working... but this did it! WHOOT!!! Thank you <3
0

Maybe this

let arr = [{"id":1,"type":"player","init":27},
 {"id":2,"type":"player","init":4},
 {"id":1,"type":"enemy","init":17}];

function compare(a, b) {
  return a.init < b.init ? -1 : 1;
}

let sorted = arr.sort(compare);
console.log(sorted);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.