How can this array manipulation problem be solved scalably?

I am working with JS and came across an interesting Array manipulation problem. I’m aware that the problem can be solved with a tremendous if – else if clause, but am actually looking for a more scalable answer.

I have two arrays (let’s call them input and output) whose contents are related to each other. The first array contains a list of ids, and the second array is actually a response from an API (I have no power over the API) matching the ids of the input array.


Examples: If I have an input array of [1, 2, 3] I will end up with an output array of

[
  { id: 1, data: "Some data for id 1" },
  { id: 2, data: "Some data for id 2" },
  { id: 3, data: "Some data for id 3" }
]

So far so good. However, the problem arises if I have an input array like [1, 2, 2], which is possible and intentional. In this situation I end with an output array of

[
  { id: 1, data: "Some data for id 1" },
  { id: 2, data: "Some data for id 2" }
]

In the above case I would need to have the output array be of length === 3 and the third item to be a copy of the second item like so

[
  { id: 1, data: "Some data for id 1" },
  { id: 2, data: "Some data for id 2" },
  { id: 2, data: "Some data for id 2" }
]

Two more examples for clarity:
Input: [4, 4, 4], what I get:

[
  { id: 4, data: "Some data for id 4" }
]

What I need to achieve:

[
  { id: 4, data: "Some data for id 4" },
  { id: 4, data: "Some data for id 4" },
  { id: 4, data: "Some data for id 4" }
]

Last one, input: [3, 3, 7]
What I get:

[
  { id: 3, data: "Some data for id 3" },
  { id: 7, data: "Some data for id 7" }
]

What I need to achieve:

[
  { id: 3, data: "Some data for id 3" },
  { id: 3, data: "Some data for id 3" },
  { id: 7, data: "Some data for id 7" },
]

I am working with a maximum array length of three, so an if-else clause comparing lengths and values is sufficient for this, but is there a dynamic and scalable way to manipulate the output array in the intended way? I was not able to think if anything from my mind.

Thanks in advance!

82 thoughts on “How can this array manipulation problem be solved scalably?”

  1. 237443 679219Hiya. Very cool internet site!! Man .. Beautiful .. Amazing .. I will bookmark your internet internet site and take the feeds additionallyI am happy to discover numerous valuable information here within the post. Thank you for sharing 630599

    Reply

Leave a Comment