Please see below code, array filter explicitly return true can remove array holes, why is this happening?
const array = [0, null, '', undefined, , ,];
console.log(array);
// => [0, null, "", undefined, empty × 2]
array.filter(() => true);
// => [0, null, "", undefined]
Because, like other array methods, .filter only iterates over properties which are directly on the array object. See the spec:
5. Let A be ? ArraySpeciesCreate(O, 0).
6. Let k be 0.
7. Let to be 0.
8. Repeat, while k < len
a. Let Pk be ! ToString(k).
b. Let kPresent be ? HasProperty(O, Pk). // <-----------------------------------
c. If kPresent is true, then
i. Let kValue be ? Get(O, Pk).
ii. Let selected be ! ToBoolean(? Call(callbackfn, T, « kValue, k, O »)).
iii. If selected is true, then
1. Perform ? CreateDataPropertyOrThrow(A, ! ToString(to), kValue).
2. Set to to to + 1.
d. Set k to k + 1.
9. Return A.
The newly created array will only have a maximum length of the number of own array-index properties on the original array.
const array = [0, null, '', undefined, , ,];
console.log(array.hasOwnProperty('3'));
console.log(array.hasOwnProperty('4'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With