LeetCode Question - 2634. Filter Elements from Array

550 Views Asked by At

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

There are 2 best solutions below

0
Unmitigated On BEST ANSWER

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 with for (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 use Array#forEach which passes the index to its callback, or a standard index-based for loop.

arr.forEach((x, i) => {
    if (fn(x, i)) filteredArr.push(x);
});
0
Oleh Kosarenko On

Because you use for...in:

var filter = (arr, fn) => {
    let filteredArr = [];
    for(const i in arr){
        console.log(typeof i)
        if(fn(arr[i], Number(i)))  filteredArr.push(arr[i])
    }
    return filteredArr;
};

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:

var filter = (arr, fn) => {
    let filteredArr = [];
    for(let i=0; i<arr.length; i++){
        if(fn(arr[i], i))  filteredArr.push(arr[i])
    }
    return filteredArr;
};