As the question states I have an array which may or may not contain empty elements. I want to reverse this array. After using the reverse
operation all the empty elements are made non-empty and thus, can be iterated. Why is this even allowed and how can I preserve the elements in the reversed array?
const originalArray = new Array(5);
originalArray[2] = "a";
originalArray.push("b");
originalArray.push("c");
const reversedArray = Array.from(originalArray).reverse();
console.log('');
console.log('original');
originalArray.forEach((el, index) => console.log('el: ', el, ' index: ', index));
console.log('');
console.log('reversed');
reversedArray.forEach((el, index) => console.log('el: ', el, ' index: ', index));
/*
Output is as follows:
original:
el: a index: 2
el: b index: 5
el: c index: 6
reversed:
el: c index: 0
el: b index: 1
el: undefined index: 2
el: undefined index: 3
el: a index: 4
el: undefined index: 5
el: undefined index: 6
I would have expected that there are still empty elements in the reversed array.
*/