{"id":3386,"date":"2015-04-04T04:24:29","date_gmt":"2015-04-04T04:24:29","guid":{"rendered":"http:\/\/www.gubatron.com\/blog\/?p=3386"},"modified":"2015-04-04T04:28:18","modified_gmt":"2015-04-04T04:28:18","slug":"how-to-make-a-foreach-function-in-javascript","status":"publish","type":"post","link":"https:\/\/www.gubatron.com\/blog\/how-to-make-a-foreach-function-in-javascript\/","title":{"rendered":"How to make a &#8220;foreach&#8221; function in JavaScript"},"content":{"rendered":"<p>I thought this would be a simple exercise in case of having to interview someone for a JavaScript position.<\/p>\n<p>&#8220;How would you make your own &#8216;foreach&#8217; in JavaScript&#8221;<\/p>\n<p>I came up with the following solution:<\/p>\n<pre><code class=\"javascript\">\/\/ \n\/\/ collection: A list of objects.\n\/\/ onElementIterationCallback: The function to be called on every element iterated\n\/\/    taking the following parameters:    foo(collection : [T], currentIndex : int)\nfunction foreach(collection, onElementIterationCallback) {\n    for (var i in collection) {\n        if (collection.hasOwnProperty(i)) {\n            onElementIterationCallback(collection[i], i);\n        }\n    }\n}\n<\/code><\/pre>\n<p>This is how you&#8217;d use it:<\/p>\n<pre><code>var sumOfAges = 0;\nvar people = [ {name:\"Angel\", age:35},\n               {name:\"Paulina\", age:33},\n               {name:\"Nicole\", age:16}]\n\nforeach(people, function (person, currentOffset) {\n   console.log(\"(\"+ currentOffset + \") iterating on \" + \n               person.name + \", age: \" + person.age);\n   sumOfAges += person.age; \n});\n\nconsole.log(sumOfAges);\n<\/code><\/pre>\n<p>The expected output would be:<\/p>\n<pre><code>(0) iterating on Angel, age: 35\n(1) iterating on Paulina, age: 33\n(2) iterating on Nicole, age: 16\n84\n<\/code><\/pre>\n<p>Hope you enjoyed, just a simple exercise of lists, creativity and callbacks.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I thought this would be a simple exercise in case of having to interview someone for a JavaScript position. &#8220;How would you make your own &#8216;foreach&#8217; in JavaScript&#8221; I came up with the following solution: \/\/ \/\/ collection: A list of objects. \/\/ onElementIterationCallback: The function to be called on every element iterated \/\/ taking [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[15,30,1],"tags":[],"class_list":["post-3386","post","type-post","status-publish","format-standard","hentry","category-code","category-geeklife","category-uncategorized"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p5Unzf-SC","jetpack-related-posts":[{"id":2193,"url":"https:\/\/www.gubatron.com\/blog\/get-a-randomly-weighted-key-in-a-mapdictionaryassociative-array\/","url_meta":{"origin":3386,"position":0},"title":"Get a randomly weighted key in a Map\/Dictionary\/Associative Array","author":"gubatron","date":"March 15, 2011","format":false,"excerpt":"Here's a very useful function to retrieve a randomly weighted key from an associative array in PHP. Sometimes you need to fetch random elements from a collection but you need some elements to have a little more chance than others to be fetched (business rules or whatever...) [php] srand(time()); \/\/dont\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3070,"url":"https:\/\/www.gubatron.com\/blog\/scala-notes-difference-between-list-foreach-and-list-map\/","url_meta":{"origin":3386,"position":1},"title":"#SCALA #NOTES Difference between list.foreach() and list.map()","author":"gubatron","date":"June 11, 2013","format":false,"excerpt":"[scala]val l = List(1,2,3,4,5) val lAfterForEach = l.foreach(x => x * 10) val lAfterMap = l.map(x => x * 10) println(\"Original List: \" + l) println(\"For each operates on each element, returns nothing:\" + lAfterForEach) println(\"Map is like foreach but returns new post-processed list: \" + lAfterMap)[\/scala] output: [bash]Original List:\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2632,"url":"https:\/\/www.gubatron.com\/blog\/javascript-get-n-random-elements-from-a-list\/","url_meta":{"origin":3386,"position":2},"title":"javascript: Get N random elements from a List","author":"gubatron","date":"January 5, 2012","format":false,"excerpt":"[javascript] \/** * Walks linearly through the list to find an element. * returns true if it's found. *\/ function elementIn(collection, element) { for (var i=0; i < collection.length; i++) { if (collection[i]==element) { return true; } } return false; } \/** * Returns a new list of n random\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":3,"url":"https:\/\/www.gubatron.com\/blog\/javascript-quicksort-implementation-with-dynamic-comparator\/","url_meta":{"origin":3386,"position":3},"title":"Javascript Quicksort implementation with dynamic comparator.","author":"gubatron","date":"February 29, 2012","format":false,"excerpt":"[javascript] Array.prototype.swap=function(a, b) { var tmp=this[a]; this[a]=this[b]; this[b]=tmp; } function quickSort(array,comparator) { qsort(array,0,array.length,comparator); } \/** * NOTE: the comparator is a dynamic function you will define like so comparator(a,b) { if (a > b) return 1; else if (a < b) return -1; else { return 0; } } *\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2671,"url":"https:\/\/www.gubatron.com\/blog\/how-to-shuffle-a-listarray-in-javascript\/","url_meta":{"origin":3386,"position":4},"title":"How to shuffle a List (or Array) in Javascript","author":"gubatron","date":"February 24, 2012","format":false,"excerpt":"[javascript] \/** * Returns number starting from offset up to n-1 *\/ function getRandomWithOffset(n,offset) { return Math.floor(Math.random()*n+offset); } \/** * Returns random integer from 0 to n-1 *\/ function getRandom(n) { return getRandomWithOffset(n,0); } \/** Fisher\u2013Yates shuffle algorithm O(n) *\/ function shuffleList(list) { for (var i=list.length-1; i>0; i--) { var\u2026","rel":"","context":"In &quot;Code&quot;","block_context":{"text":"Code","link":"https:\/\/www.gubatron.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2233,"url":"https:\/\/www.gubatron.com\/blog\/twitterautolinks-jquery-extension-to-replace-twitter-names-for-links-to-their-respective-pages\/","url_meta":{"origin":3386,"position":5},"title":"twitterAutoLinks: jQuery extension to replace twitter @names for links to their respective pages.","author":"gubatron","date":"August 2, 2011","format":false,"excerpt":"Save the following on a .js file, preferably named jquery.twitterAutoLinks.js [javascript] \/** Auto replace all Twitter nicknames for links *\/ $.fn.twitterAutoLinks = function() { return this.each(function() { var html = $(this).html(); $(this).html(html.replace(\/B@([w-]+)\/gm, '<a href=\"http:\/\/twitter.com\/$1\" target=\"_blank\">@$1<\/a>')); }); }; [\/javascript] Usage After importing the jquery.twitterAutoLinks.js file (make sure it's after you've imported\u2026","rel":"","context":"In &quot;AJAX&quot;","block_context":{"text":"AJAX","link":"https:\/\/www.gubatron.com\/blog\/category\/ajax\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/3386","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/comments?post=3386"}],"version-history":[{"count":6,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/3386\/revisions"}],"predecessor-version":[{"id":3393,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/posts\/3386\/revisions\/3393"}],"wp:attachment":[{"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/media?parent=3386"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/categories?post=3386"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gubatron.com\/blog\/wp-json\/wp\/v2\/tags?post=3386"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}