I would like to read your opinions on this issue…
I have two arrays. One has three items ['A', 'C', 'E'] and the other has two items ['B', 'D']. I need to combine them like this: 'ABCDE'.
I came up with two solutions
first:
const arrayOne = ['A', 'C', 'E'];
const arrayTwo = ['B', 'D'];
let result = arrayOne.shift();
for (let i = 0; i < arrayOne.length; i++) {
result += arrayTwo[i] + arrayOne[i];
}
console.log(result);
// ABCDE
Why? That’s a good way to write bugs. You can handle the case where the two arrays come in a different order, and the case where one array is much longer than the other with some small changes.
Why would you want a solution that may fail one day? This is a real issue in development. You have a battle between what is the bare minimum to meet the immediate needs and what would be “fool proof” in the future. In reality, neither is “correct” and we often have to make compromises and make tough decisions.
But in this case, a robust solution is easier than what you are trying to do:
const result = arrayOne.concat(arrayTwo).sort().join('');
That is more compact, easier to read, and will work no matter how many are in each and what order they start out in. What does it cost you? A tiny bit of pride and it takes 0.00017 seconds longer. In general, that’s a great trade off.