N
N
nurdus2017-10-22 23:47:02
Python
nurdus, 2017-10-22 23:47:02

Why does array.filter ignore the value 0 (not index)?

Good evening.
Faced strange behavior of array.filter(), maybe I'm confusing something:

const xArray = [0, 1, 2, 3, 4, 5];
let xArray2 = xArray.filter((x) => {
  if (0 <= x && x <= 10) {
    console.log('x ' + x); // тут 0 обрабатывается
    return x;
  }
});
console.log(xArray2); // [1, 2, 3, 4, 5]
xArray3 = []
for(i = 0; i < xArray.length; i++) {
  if (0 <= xArray[i] && xArray[i] <= 10) {
    xArray3[i] = xArray[i];
  }
}
console.log(xArray3); // [0, 1, 2, 3, 4, 5]

Why does filter ignore the value "0"? If instead of "0" put something else, then everything is ok.
https://jsfiddle.net/nurdus/hhk438sm/2/

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
origami1024, 2019-07-24
@Web__Nikita03

This is the expected type of the variable, or you can include a string annotation there.
https://www.python.org/dev/peps/pep-3107/

A
Alexander Gontarev, 2017-10-22
@nurdus

1) it is not clear what you want to get at the output
2) the callback should return a boolean value, if it is true, then item remains, and if it is false, then it is "deleted", and if we return 0, then it will be cast to it, right, to false,

const xArray = [-1, 0, 1, 2, 3, 4, 5, 11];
let xArray2 = xArray.filter((x) => {
  return 0 <= x && x <= 10;
});
xArray2;  // [0, 1, 2, 3, 4, 5]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question