When I try to run this code without the Number(), it doesn't work.
ar filter = (arr, fn) => {
let filteredArr = [];
for(const i in arr){
if(fn(arr[i], Number(i))) filteredArr.push(arr[i])
}
return filteredArr;
};
I don't understand why this code doesn't work without the Number(), if the index is some number, at least 0, it's a integer, then it should work... Could you help me? I would be really grateful.
The
for...inloop iterates over enumerable string properties. All the indexes used to access elements of an array are such properties, so you need to convert each index to a number when iterating withfor (const i in arr).Note that it is generally a very bad idea to use this form of loop when you want to access indexes. If you cannot use
Array#filter, you could useArray#forEachwhich passes the index to its callback, or a standard index-basedforloop.