DEV Community

Discussion on: Why is using javascript “for loop” for array iteration a bad idea?

Collapse
 
peerreynders profile image
peerreynders • Edited

It doesn't matter what function you pass to filter() - it skips holes.

const list = [, , { level: { deep: 3 } }, ,];
const predicate = (o) => o.level.deep > 0;

console.log(list.filter(predicate));
// [{ level: { deep: 3}}]
Enter fullscreen mode Exit fullscreen mode

ECMAScript 6: holes in Arrays.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I imagine you misunderstood my code

Thread Thread
 
peerreynders profile image
peerreynders • Edited

I imagine that you were trying to use

console.log(Boolean(undefined)); // false
Enter fullscreen mode Exit fullscreen mode

to sanitize the array. However observe

// sparse array - i.e. has holes
const a = [, , 2, , ,];
// dense array - no holes
const b = [undefined, undefined, 2, undefined, undefined];

console.log(`a: ${a.length}`); // "a: 5" i.e. last comma is treated as a trailing comma
console.log(`b: ${b.length}`); // "b: 5"

function predicate(value, index) {
  console.log(index);
  return Boolean(value);
}

const af = a.filter(predicate); // 2
const bf = b.filter(predicate); // 0, 1, 2, 3, 4

console.log(af); // [2]
console.log(bf); // [2]
Enter fullscreen mode Exit fullscreen mode

i.e. holes are skipped, actual undefined values are not.

So the function passed to filter() never gets to make a decision about the holes.

sparse arrays vs. dense arrays

Thread Thread
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

The intent is to remove All falsey values which I admit is a bit of a hammer and yes I can see your point, filter ignores empties, but it still cleans an array which is my point.

To anyone not aware, This is a well known trick which removes ALL falsey value.

If you want to handle falsey valuess such as 0, -n, false, null, undefined, write a better predicate function, my demo is just that, a quick demo of principal, prepare your inputs.