Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 javascript Difference between foreach and each

What is the difference between forEach and each in D3js?

like image 633
Kuan Avatar asked Nov 20 '12 02:11

Kuan


People also ask

What is the difference between forEach and each?

each differs for the arguments passed to the callback. If you use _. forEach , the first argument passed to the callback is the value, not the key. So if you don't bother at all about the key you should use _.

What is the difference between forEach () and map ()?

The main difference between map and forEach is that the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn't return anything. You can use the forEach method to mutate the source array, but this isn't really the way it's meant to be used.

When should you not use forEach?

one reason not to use foreach at least in java is that it will create an iterator object which will eventually be garbage collected. Thus if you are trying to write code that avoids garbage collection it is better to avoid foreach.


1 Answers

First, .forEach() is not part of d3, it's a native function of javascript arrays. So,

["a", "b", "c"].forEach(function(d, i) { console.log(d + " " + i); }); // Outputs: a 0 b 1 c 2 

And that works even if d3 is not loaded on the page.

Next, d3's .each() works on d3 selections (what you get when you d3.selectAll(...)). Technically, you can call .forEach() on a d3 selection, since behind the scenes, a d3 selection is an array with extra functions (one of them is .each()). But you shouldn't do that because:

  1. Doing so will not produce the desired behavior. Knowing how to use .forEach() with a d3 selection in order to produce any desired behavior would require intimate understanding of the inner workings of d3. So why do it, if you can just use the documented, public part of the API.

  2. When you call .each(function(d, i) { }) on a d3 selection, you get more than just d and i: the function gets invoked such that the this keyword anywhere inside that function points to the HTML DOM element associated with d. In other words console.log(this) from inside function(d,i) {} will log something like <div class="foo"></div> or whatever html element it is. And that's useful, because then you can call function on this this object in order change its CSS properties, contents or whatever. Usually, you use d3 to set these properties, as in d3.select(this).style('color', '#c33');.

The main takeaway is that, using .each() you get access to 3 things you need: d, this and i. With .forEach(), on an array (like in the example from the beginning) you only get 2 things (d and i), and you'd have to do a bunch of work to also associate an HTML element with those 2 things. And that, among other things, is how d3 is useful.

like image 157
meetamit Avatar answered Sep 16 '22 11:09

meetamit