Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  16] [ 4]  / answers: 1 / hits: 26367  / 10 Years ago, sun, june 22, 2014, 12:00:00

Is there a forEach loop in Lodash for associative arrays? The function called forEach, I've found, only works for indexed arrays. For example, if I have an array myArray with values [1, 2, 3], and do



lodash.forEach(myArray, function(index) {
console.log(index);
});


and run the function (in Node), I get the expected result:



1
2
3


However, when I try this with an associative array, it doesn't work:



lodash = require('lodash');
myArray = [];
myArray['valOne'] = 1;
myArray['valTwo'] = 2;
myArray['valThree'] = 3;
lodash.forEach(myArray, function(index) {
console.log('7');
});


As you can see from running this in Node, the callback function doesn't fire even when it includes something other than the array elements. It just seems to skip the loop entirely.



First of all, why does this happen? Second of all, is there another function included in Lodash for this problem, or, if not, is there a way to use the forEach function to accomplish this, without changing the original array in the process?


More From » arrays

 Answers
92

Lodash has the function forOwn for this purpose. In the second array, if you do



_.forOwn(myArray, function(index) {
console.log(index);
});


you should get the intended result.



I'm still not sure why forEach seems to skip the first function, however, but I believe it may have to do with the array not having a length. A JavaScript array's length is the highest numbered index it has. For example, an array myOtherArray defined as myOtherArray[999]=myValue will have a length of 1,000 (because arrays are zero-indexed, meaning they start at 0, not 1), even if it has no other values. This means an array with no numbered indexes, or only negative indexes, will not have a length attribute. Lodash must be picking up on this and not giving the array a length attribute, likely to maintain consistency and performance, thus not rendering any output.


[#70483] Thursday, June 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mary

Total Points: 432
Total Questions: 98
Total Answers: 98

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;