Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in array reads 'remove'? [duplicate]

Tags:

javascript

I just experienced the strangest thing, this is the code I'm actually using :

for (iter in data.List) {
    console.log(iter);
}

As you would expect, the log should give the number of each row (0, 1, 2...), instead it gives me this :

0
1
2
remove

Knowing that my array only has 3 rows

Did anybody ever encountred this ?

like image 649
Mehdiway Avatar asked Aug 07 '13 12:08

Mehdiway


People also ask

How do you remove duplicate values from an array loop?

We can solve this problem using two loops: The outer loop i traverses the entire array. The inner loop j traverses the remaining array from the i+1 position. At any time while traversing, if elements at positions i and j are equal, then we will break the inner loop and continue with the outer loop.

How do you remove duplicates from an array of arrays?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

Which function is used to remove duplicate values from an array?

The array_unique() function removes duplicate values from an array.

Does remove duplicates remove the entire row?

This method will introduce the Remove Duplicates feature to remove entire rows based on duplicates in one column easily in Excel. 1. Select the range you will delete rows based on duplicates in one column, and then click Data > Remove Duplicates.


2 Answers

Basically, the problem is that you are iterating through your array using a for in loop, which is not meant for iteratung through arrays. Its intent is to iterate through all properties of an object, and apparently there is a property called remove on your array.

For more details on why for in is a bad idea when it comes to arrays, see Why is using "for...in" with array iteration a bad idea?.

As solution, I'd suggest to use an indexed for loop. This type of loop does not care about properties, hence you are fine. So it basically comes down to a very classical:

for (var i = 0; i < data.List; i++) {
  console.log(data.List[i]);
}

By the way: You should not uppercase anything in JavaScript, unless it's a constructor function. Hence it should be data.list.

PS: A nice read when it comes to arrays and (mis-)using them, read Fun with JavaScript Arrays, a quite good read.

like image 142
Golo Roden Avatar answered Oct 07 '22 09:10

Golo Roden


Yes, that is how for..in works in JavaScript. It enumerates over all object properties (not Array indexes). Simple solution: don't use for..in on Arrays, because that's not what it is for.

like image 22
RoToRa Avatar answered Oct 07 '22 09:10

RoToRa