0

I have an array with a size of 5 and in each element, I fill in with a corresponding subarray, like this:

let equalSums = new Array(5);
    for (let i = 0; i < equalSums.length; i++) {
        equalSums[i] = new Array(5);
}
console.log(equalSums);
/*
[ [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ] ]
*/

And after malnipulating to find contigous subarray that equal to a give number (in this case it's 3), I push subarray with sum elements equal 3 to this equalSum array, and now it looks like this:

[ [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ 1, 2 ],
  [ 2, 1 ],
  [ 3 ] ]

The problem is I want to remove all the empty subarrays, then I do the following:

let rs = equalSums.filter(e => e.every(x => x != ""));
console.log(rs);
/* 
[ [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ , , , ,  ],
  [ 1, 2 ],
  [ 2, 1 ],
  [ 3 ] ]
/*

Still the same, it doesn't remove the empty subarrays.

But, I use some instead, it gives me the desired result:

let rs = equalSums.filter(e => e.some(x => x != ""));
console.log(rs);
/*
[ [ 1, 2 ], [ 2, 1 ], [ 3 ] ]
*/

Can anybody explain for me why every doesn't work and some does?

Nam V. Do
  • 630
  • 6
  • 27

2 Answers2

0

The sparse [,,,,] arrays you have there essentially have no elements, only spaces that are occupied by nothing.

So [,,,,,].every(x => x != '') asks, "Are all of this array's elements unequal to ""?" And the answer is Yes. It has no elements, so all of the elements it has (none) are unequal to "".

[,,,,].some(x => x != "") asks, "Does this array have any elements that are unequal to ""?" And the answer is No. It has no elements, so it doesn't have any that are unequal to "".

You haven't really explained why you're using all these sparse arrays, and I suspect you might be going about whatever you're trying to do in the wrong way, but at least this explains what you are seeing with every and some.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Looks good to me, I guess this answer explains why some and every have different return values for the same case, it because they are phrasing the question differently. – Younes El Alami Dec 20 '19 at 05:23
0

Please note that [,,,,] is considered to be an empty array and will behave the same way as [] when using every and some even tho it says it has a length of 4. more info on that

every and some return different values if you call them on an empty array.

[].every(x => x)
true
[].some(x => x)
false

Your code seem to rely on this behavior to filter out empty arrays, your check x != "" is not what doing the filtering.

Younes El Alami
  • 191
  • 1
  • 5