skip to Main Content

For a chess app, I need to sort this array based on the value in javascript:

[e7e5: '-42', g8f6: '-16', h7h6: '-38', c8d7: '-29']

Something along the lines:

Moves.sort((a,b)=>a.?? > b.??))

Whereby, the missing bit to get it to work is the ??.

Have look on the net for a solution, but could not find.

Any help would be appreciated.

David

2

Answers


  1. movesArray.sort((a, b) => parseInt(b[1]) – parseInt(a[1]));
    This will sort the moves in descending order based on the numeric values.

    Login or Signup to reply.
  2. Use Object.values() to get a value of a property regardless of its name in an object:

    const Moves = [{e7e5: '-42'}, {g8f6: '-16'}, {h7h6: '-38'}, {c8d7: '-29'}];
    
    Moves.sort((a,b) => Object.values(a)[0] - Object.values(b)[0]);
    
    console.log(Moves);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search