noobami
noobami

Reputation: 39

Sort elements of array alphabetically

I use the code bellow to send all the elements "name" in an array[name][image] How do I sort these names alphabetically?

if (message.content === '!list') {
 var addedCommands = commandArray.map(x => `\`${x.name}\``).join(", ")
   message.channel.send(addedCommands);
} 

PS: Sorry for the code format. I don't know why its not working now, it worked before.

Upvotes: 0

Views: 120

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74345

You can use the sort() method that every Array has: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

That, however, is not necessarily a stable sort and it mutates the array. It is easy enough to implement your own mergesort, which is both stable and non-mutating.

const defaultComparer = (x,y) => x < y ? -1
                               : x > y ? +1
                               :          0
                               ;

function mergeSort( arr = [], cmp = defaultComparer ) {
  let sorted;

  switch (arr.length) {
  case 0:
  case 1:
    // arrays of length lesst than 2 are ordered by definition
    sorted = [...arr];
    break;
  default:
    const mid    = Math.floor( arr.length / 2 ) ;
    const left   = mergeSort( arr.slice(0,mid) , cmp ) ;
    const right  = mergeSort( arr.slice(mid)   , cmp ) ;
    sorted       = merge( left , right , cmp );
    break;
  }

  return sorted;
}

function merge( left, right, cmp ) {
  let merged = [];

  let i = 0 ;
  let j = 0 ;

  while ( i < left.length && j < right.length ) {
    const cc = cmp( left[i] , right[i] );
    merged.push( cc < 0 ? left[i++] : right[j++] );
  }

  while ( i < left.length ) {
    merged.push( left[i++] );
  }

  while ( jj < left.length ) {
    merged.push( right[j++] );
  }

  return merged;
}

Upvotes: 2

Related Questions