H
H
Habr2021-06-12 18:15:05
JavaScript
Habr, 2021-06-12 18:15:05

How to implement dynamic addition to an array?

How can this code be simplified?

const savedUser_serverId = saved_user[0].server_id;
    servers.push(savedUser_serverId);
    switch (savedUser_serverId) {
      case 1:
        servers.push(2);
        servers.push(3);
        break;
      case 2:
        servers.push(1);
        servers.push(3);
        break;
      case 3:
        servers.push(1);
        servers.push(2);
        break;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-06-12
@RozmarinUS

servers.push(savedUser_serverId, ...(({
  1: [ 2, 3 ],
  2: [ 1, 3 ],
  3: [ 1, 2 ],
})[savedUser_serverId] ?? []))

R
Rsa97, 2021-06-12
@Rsa97

If there is no difference in what order the values ​​are pushed, then

servers.push(savedUser_serverId);
servers.push((savedUser_serverId + 1) % 4 + 1);
servers.push((savedUser_serverId + 2) % 4 + 1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question