javascriptdistinct-values

LeetCode Question - 2634. Filter Elements from Array


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.


Solution

  • 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);
    });