noobami
noobami

Reputation: 39

Loop 100 array elements at a time?

I have a commandArray.json file with 300+ comands+imagelinks in the format commandArray[name][response]

I used the code bellow to show users the command names, but its seems i've reached the discord limit of 2000 characters in a single chat message. So I'm thinking of sending about 100 command names at a time.

Can you help me implement somekind of loop that achieves this?

The code first splits the names and turns the json objects into string and then sorts alphabetically and joins in a string to send the message.

I just need to count 100 names and then send message, and it there are more count again and send and so on.

const commandArray = require("./commandArray.json");

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

}

Upvotes: 1

Views: 1302

Answers (2)

bburhans
bburhans

Reputation: 569

const chunkSize = 100, chunks = [];
for (let i = 0; i < Math.ceil(commandArray.length / chunkSize); i++) {
  chunks[i] = commandArray.slice(i*chunkSize, (i+1)*chunkSize);
}

Then just operate on chunks instead of commandArray above, sending each chunk as its own message, e.g. for (chunk of chunks) ... send(chunk.map().sort().join()). Also, you don't need the first .join() followed by a .split(), which does almost nothing here.

Try this:

// outside your message handler...

const commandArray = require("./commandArray.json");
commandArray.sort((a, b) => a.name > b.name ? 1 : 0);

const chunkSize = 100, chunks = [];
for (let i = 0; i < Math.ceil(commandArray.length / chunkSize); i++) {
  chunks[i] = commandArray.slice(i*chunkSize, (i+1)*chunkSize);
}

// inside your message handler function...

if (message.content === '!commands') {
  for (chunk of chunks) {
    message.channel.send(chunk.map(x => `\`${x.name}\``).join(', '));
  }
}

Upvotes: 3

ksav
ksav

Reputation: 20840

lodash has a utility called chunk which

Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.

import chunk from "lodash.chunk";
const commandArray = require("./commandArray.json");


if (message.content === "!commands") {
  const chunked = chunk(commandArray.sort(), 100);
  chunked.forEach((c, i) => {
    const addedCommands = c.map((x) => `\`${x.name}\``).join(", ");
    message.channel.send(addedCommands);
  });
}

Edit morning-cloud-90tke

Upvotes: 0

Related Questions