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.
2
Answers
Because you use for…in:
This loop is used for objects and is not recommended for arrays.
You can try to use the loop for that consists of three optional expressions:
The
for...in
loop 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#forEach
which passes the index to its callback, or a standard index-basedfor
loop.