【问题标题】:Sorting alphabetically the first elements of an array like - arr[name][image]?按字母顺序对数组的第一个元素进行排序,例如 - arr[name][image]?
【发布时间】:2021-09-05 07:19:45
【问题描述】:

我在 json 中有一个包含 100 张图像的数组,格式如下:

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

我想以列表的形式打印所有“名称”元素,而不是图像。

我尝试在下面的代码中将 json 转换为字符串。我也想按字母顺序排序。 我想我需要一个循环?还是有更好的方法?

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

【问题讨论】:

    标签: javascript arrays sorting discord.js alphabetical


    【解决方案1】:

    我首先使用 JSON.parse() 将 JSON 转换为数组,然后使用自定义比较函数对图像进行排序,该函数仅按 name 字段的升序排序。然后我映射排序后的数组并返回一个新数组,该数组仅包含每个元素的 name 字段,然后打印它。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      相关资源
      最近更新 更多