Home > Enterprise >  How to filter an object inside 2D array in JavaScript?
How to filter an object inside 2D array in JavaScript?

Time:09-03

I tried to filter a message in Discord.js based on its author and the message type.

Here's the raw data:

[
  [
    {
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256144094175392",
      "createdTimestamp": 1662126327299,
      "type": 0,
      "system": false,
      "content": "https://youtube.com",
      "authorId": "530963824396992514",
      "pinned": false,
      "tts": false,
      "nonce": "1015256103077806080",
      "embeds": [
        {
          "type": "link",
          "url": "https://youtube.com/",
          "title": "YouTube",
          "description": "Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.",
          "thumbnail": {
            "url": "https://www.youtube.com/img/desktop/yt_1200.png",
            "proxy_url": "https://images-ext-1.discordapp.net/external/Y9ec_ju_jMFXEYbE-Ie5kPp5R5im0556dCBV7EPvn8M/https/www.youtube.com/img/desktop/yt_1200.png",
            "width": 1200,
            "height": 1200
          }
        }
      ],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "https://youtube.com"
    },
    {
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256128810123335",
      "createdTimestamp": 1662126323655,
      "type": 0,
      "system": false,
      "content": "test 2",
      "authorId": "530963824396992514",
      "pinned": false,
      "tts": false,
      "nonce": "1015256087244308480",
      "embeds": [],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "test 2"
    }
  ],
  [
    {
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256083968835594",
      "createdTimestamp": 1662126312964,
      "type": 0,
      "system": false,
      "content": "https://whatsapp.com",
      "authorId": "755312683632427120",
      "pinned": false,
      "tts": false,
      "nonce": "1015256042948263936",
      "embeds": [
        {
          "type": "link",
          "url": "https://whatsapp.com/",
          "title": "WhatsApp",
          "description": "WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.",
          "color": 1812113,
          "provider": {
            "name": "WhatsApp.com"
          },
          "thumbnail": {
            "url": "https://static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
            "proxy_url": "https://images-ext-2.discordapp.net/external/6KlN83vXntceA4ZV7gjYQYA_paQh7uOmhGDYm7td1rQ/https/static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
            "width": 1200,
            "height": 630
          }
        }
      ],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "https://whatsapp.com"
    },
    {
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256016490856488",
      "createdTimestamp": 1662126296876,
      "type": 0,
      "system": false,
      "content": "test",
      "authorId": "755312683632427120",
      "pinned": false,
      "tts": false,
      "nonce": "1015255975403192320",
      "embeds": [],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "test"
    }
  ]
]

and i want to format it to something like:

[
    [
        [
            {
                "channelId": "862033838896185376",
                "guildId": "791708642813411358",
                "id": "1015256144094175392",
                "createdTimestamp": 1662126327299,
                "type": 0,
                "system": false,
                "content": "https://youtube.com",
                "authorId": "530963824396992514",
                "pinned": false,
                "tts": false,
                "nonce": "1015256103077806080",
                "embeds": [
                    {
                        "type": "link",
                        "url": "https://youtube.com/",
                        "title": "YouTube",
                        "description": "Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.",
                        "thumbnail": {
                            "url": "https://www.youtube.com/img/desktop/yt_1200.png",
                            "proxy_url": "https://images-ext-1.discordapp.net/external/Y9ec_ju_jMFXEYbE-Ie5kPp5R5im0556dCBV7EPvn8M/https/www.youtube.com/img/desktop/yt_1200.png",
                            "width": 1200,
                            "height": 1200
                        }
                    }
                ],
                "components": [],
                "attachments": [],
                "stickers": [],
                "editedTimestamp": null,
                "mentions": {
                    "everyone": false,
                    "users": [],
                    "roles": [],
                    "crosspostedChannels": [],
                    "repliedUser": null,
                    "members": [],
                    "channels": []
                },
                "webhookId": null,
                "groupActivityApplicationId": null,
                "applicationId": null,
                "activity": null,
                "flags": 0,
                "reference": null,
                "interaction": null,
                "cleanContent": "https://youtube.com"
            }
        ],
        [
            {
                "channelId": "862033838896185376",
                "guildId": "791708642813411358",
                "id": "1015256128810123335",
                "createdTimestamp": 1662126323655,
                "type": 0,
                "system": false,
                "content": "test 2",
                "authorId": "530963824396992514",
                "pinned": false,
                "tts": false,
                "nonce": "1015256087244308480",
                "embeds": [],
                "components": [],
                "attachments": [],
                "stickers": [],
                "editedTimestamp": null,
                "mentions": {
                    "everyone": false,
                    "users": [],
                    "roles": [],
                    "crosspostedChannels": [],
                    "repliedUser": null,
                    "members": [],
                    "channels": []
                },
                "webhookId": null,
                "groupActivityApplicationId": null,
                "applicationId": null,
                "activity": null,
                "flags": 0,
                "reference": null,
                "interaction": null,
                "cleanContent": "test 2"
            }
        ]
    ],
    [
        [
            {
                "channelId": "862033838896185376",
                "guildId": "791708642813411358",
                "id": "1015256083968835594",
                "createdTimestamp": 1662126312964,
                "type": 0,
                "system": false,
                "content": "https://whatsapp.com",
                "authorId": "755312683632427120",
                "pinned": false,
                "tts": false,
                "nonce": "1015256042948263936",
                "embeds": [
                    {
                        "type": "link",
                        "url": "https://whatsapp.com/",
                        "title": "WhatsApp",
                        "description": "WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.",
                        "color": 1812113,
                        "provider": {
                            "name": "WhatsApp.com"
                        },
                        "thumbnail": {
                            "url": "https://static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
                            "proxy_url": "https://images-ext-2.discordapp.net/external/6KlN83vXntceA4ZV7gjYQYA_paQh7uOmhGDYm7td1rQ/https/static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
                            "width": 1200,
                            "height": 630
                        }
                    }
                ],
                "components": [],
                "attachments": [],
                "stickers": [],
                "editedTimestamp": null,
                "mentions": {
                    "everyone": false,
                    "users": [],
                    "roles": [],
                    "crosspostedChannels": [],
                    "repliedUser": null,
                    "members": [],
                    "channels": []
                },
                "webhookId": null,
                "groupActivityApplicationId": null,
                "applicationId": null,
                "activity": null,
                "flags": 0,
                "reference": null,
                "interaction": null,
                "cleanContent": "https://whatsapp.com"
            }
        ],
        [
            {
                "channelId": "862033838896185376",
                "guildId": "791708642813411358",
                "id": "1015256016490856488",
                "createdTimestamp": 1662126296876,
                "type": 0,
                "system": false,
                "content": "test",
                "authorId": "755312683632427120",
                "pinned": false,
                "tts": false,
                "nonce": "1015255975403192320",
                "embeds": [],
                "components": [],
                "attachments": [],
                "stickers": [],
                "editedTimestamp": null,
                "mentions": {
                    "everyone": false,
                    "users": [],
                    "roles": [],
                    "crosspostedChannels": [],
                    "repliedUser": null,
                    "members": [],
                    "channels": []
                },
                "webhookId": null,
                "groupActivityApplicationId": null,
                "applicationId": null,
                "activity": null,
                "flags": 0,
                "reference": null,
                "interaction": null,
                "cleanContent": "test"
            }
        ]
    ]
]

The ideas is that each filtered object is wrapped by an array, so I tried this:

const linkMessage = groupedMessages.flatMap((arrMessage) => arrMessage).some((message) => isValidURL(message.content));
const embedMessage = groupedMessages.flatMap((arrMessage) => arrMessage).some((message) => message.embeds.length > 0 && message.embeds.map((emb) => emb.type === 'rich'));
const componentMessage = groupedMessages.flatMap((arrMessage) => arrMessage).some((message) => message.components.length > 0);

const responseField = [];

if (linkMessage) {
    responseField.push(
        groupedMessages.map(
            (arrMessage) =>
                `from ${userMention(arrMessage[0].author.id)}\n${arrMessage
                    .filter((message) => isValidURL(message.content))
                    .map((message) => `${message.content} (sent at ${time(new Date(message.createdTimestamp), TimestampStyles.RelativeTime)})\n`)
                    .join('')}`,
        ),
    );
}

if (embedMessage || componentMessage) {
    responseField.push(groupedMessages.map((arrMessage) => `from ${userMention(arrMessage[0].author.id)}\n${italic('No content, maybe an embed or a component.')}`));
}

but the expected output isn't same with what I wanted. I just want to create a nested array format. Can anyone help me?

EDIT

I simplify the case:

[
    [
        {
            "id": "1",
            "content": "https://youtube.com",
            "authorId": "1",
            "embeds": [...
            ]
        },
        {
            "id": "2",
            "content": "lorem ipsum.",
            "authorId": "1",
            "embeds": []
        },
        {
            "id": "3",
            "content": "",
            "authorId": "1",
            "embeds": []
        }
    ],
    [
        {
            "id": "1",
            "content": "https://whatsapp.com",
            "authorId": "2",
            "embeds": [...
            ]
        },
        {
            "id": "2",
            "content": "lorem ipsum.",
            "authorId": "2",
            "embeds": []
        },
        {
            "id": "3",
            "content": "",
            "authorId": "2",
            "embeds": []
        }
    ]
]

expected output:

[
    [

        // Link type messages (content is valid URL)
        [
            {
                "id": "1",
                "content": "https://youtube.com",
                "authorId": "1",
                "embeds": [
                    {
                        "type": "link"
                    }
                ]
            }
        ],

        // regular type messages (empty embeds data)
        [
            {
                "id": "2",
                "content": "lorem ipsum.",
                "authorId": "1",
                "embeds": []
            }
        ],

        // Embed type messages (empty content)
        [
            {
                "id": "3",
                "content": "",
                "authorId": "1",
                "embeds": [
                    {
                        "type": "rich"
                    }
                ]
            }
        ]
    ],
    [...
    ]
]

CodePudding user response:

You want to wrap every element with an array. Let's iterate the array "recursively" (it's just two levels really) looking for arrays, until we find a non-array then we wrap it and place it in place of arr[index].

Update:

  • no need for recursion since it's a known structure
  • we group sub-array items into object by type ("Link", "Regular" or "Empty")
  • finally we take the values of that object as the required array
  • update parent array in place

var msgs = [
  [{
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256144094175392",
      "createdTimestamp": 1662126327299,
      "type": 0,
      "system": false,
      "content": "https://youtube.com",
      "authorId": "530963824396992514",
      "pinned": false,
      "tts": false,
      "nonce": "1015256103077806080",
      "embeds": [{
        "type": "link",
        "url": "https://youtube.com/",
        "title": "YouTube",
        "description": "Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.",
        "thumbnail": {
          "url": "https://www.youtube.com/img/desktop/yt_1200.png",
          "proxy_url": "https://images-ext-1.discordapp.net/external/Y9ec_ju_jMFXEYbE-Ie5kPp5R5im0556dCBV7EPvn8M/https/www.youtube.com/img/desktop/yt_1200.png",
          "width": 1200,
          "height": 1200
        }
      }],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "https://youtube.com"
    },
    {
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256128810123335",
      "createdTimestamp": 1662126323655,
      "type": 0,
      "system": false,
      "content": "test 2",
      "authorId": "530963824396992514",
      "pinned": false,
      "tts": false,
      "nonce": "1015256087244308480",
      "embeds": [],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "test 2"
    }
  ],
  [{
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256083968835594",
      "createdTimestamp": 1662126312964,
      "type": 0,
      "system": false,
      "content": "https://whatsapp.com",
      "authorId": "755312683632427120",
      "pinned": false,
      "tts": false,
      "nonce": "1015256042948263936",
      "embeds": [{
        "type": "link",
        "url": "https://whatsapp.com/",
        "title": "WhatsApp",
        "description": "WhatsApp Messenger: More than 2 billion people in over 180 countries use WhatsApp to stay in touch with friends and family, anytime and anywhere. WhatsApp is free and offers simple, secure, reliable messaging and calling, available on phones all over the world.",
        "color": 1812113,
        "provider": {
          "name": "WhatsApp.com"
        },
        "thumbnail": {
          "url": "https://static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
          "proxy_url": "https://images-ext-2.discordapp.net/external/6KlN83vXntceA4ZV7gjYQYA_paQh7uOmhGDYm7td1rQ/https/static.whatsapp.net/rsrc.php/v3/yO/r/FsWUqRoOsPu.png",
          "width": 1200,
          "height": 630
        }
      }],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "https://whatsapp.com"
    },
    {
      "channelId": "862033838896185376",
      "guildId": "791708642813411358",
      "id": "1015256016490856488",
      "createdTimestamp": 1662126296876,
      "type": 0,
      "system": false,
      "content": "test",
      "authorId": "755312683632427120",
      "pinned": false,
      "tts": false,
      "nonce": "1015255975403192320",
      "embeds": [],
      "components": [],
      "attachments": [],
      "stickers": [],
      "editedTimestamp": null,
      "mentions": {
        "everyone": false,
        "users": [],
        "roles": [],
        "crosspostedChannels": [],
        "repliedUser": null,
        "members": [],
        "channels": []
      },
      "webhookId": null,
      "groupActivityApplicationId": null,
      "applicationId": null,
      "activity": null,
      "flags": 0,
      "reference": null,
      "interaction": null,
      "cleanContent": "test"
    }
  ]
]

function get_type_of_object(obj) {
  if (obj.content.startsWith("http://") || obj.content.startsWith("https://")) {
    return "Link"
  }
  if (obj.embeds.length) {
    return "Regular"
  }
  if (!obj.embeds.length) {
    return "Empty"
  }
}

function wrap_by_group(arr) {
  arr.forEach(function(sub_arr, index) {
    var collector = {}
    sub_arr.forEach(function(item) {
      var group = get_type_of_object(item);
      collector[group] = collector[group] || [];
      collector[group].push(item);
    })

    arr[index] = Object.values(collector);
  })
}

wrap_by_group(msgs);
console.log(msgs)
.as-console-wrapper {
  max-height: 100% !important;
}

  • Related