Search code examples
javascriptarrayssortingdiscord.jsalphabetical

Sorting alphabetically the first elements of an array like - arr[name][image]?


I have an array in json with 100 images in the format bellow:

[{"name":"one","image":"one.jpeg"},
 {"name":"two","image":"two.jpeg"},
 {"name":"three","image":"three.jpeg"}]

I want to print all the "name" elements in form of a list but not the images.

I tried converting the json to string in the code bellow. I also would like to sort it alphabetically. I think I need a loop? or is there a better method?

if (message.content === '!list') {
    const list= commandArray[0];
    const myJSON = JSON.stringify(list);
    message.channel.send(myJSON);
}

Solution

  • I first convert the JSON to an array using JSON.parse() and then I am sorting the images with a custom compare function that simply sorts in an ascending order by the name field. Then I map through the sorted array and return a new array containing only the name field from each element, and then I print it.

    let images_json = '[{"name":"alpha","image":"alpha.jpeg"}, {"name":"delta","image":"delta.jpeg"},{"name":"charlie","image":"charlie.jpeg"}]';
    let images = JSON.parse(images_json)
    console.log(images); //printing to console before sort
    
    images.sort(function(a, b) {
      if (a.name > b.name) {
        return 1;
      }
      if (b.name > a.name) {
        return -1;
      }
      return 0;
    });
    console.log(images); //printing to console after sort
    
    let images_names = images.map(img => img.name);
    console.log(images_names) //printing only the names of the images