Array Comprehension

By: Dusty Arlia
Published on Sunday, October 27, 2013, 04:42 PM
Last Updated on Saturday, July 11, 2015 at 6:43 PM
Total Updates: 3

Array comprehension is a way to initialize an array from another array or iterable object. Here is the basic syntax:

[expression for (variable in object) if (condition)]

Here are the 3 components to these statements:

  1. expression - The body of the loop. The results of this expression get inserted into the array that is being created.
  2. for/in or for each loop - The variable gets assigned the property values (for each) or property names (for/in) of the object. The object may be a generator, iterable object, or an array. There is an implied let keyword before the variable (the var and let keywords are not allowed before the variable name). The variable used in the array comprehension is not visible outside the square brackets and does not overwrite variables by the same name.
  3. if (condition) (optional) - Used to filter iterated values.

Examples:

names = ['Dusty', 'Sara', 'Bob'];
boook = [x for (x in names)];     //duplicates names array
touchdowns = [1,2,3];
points = [x*7 for each (x in touchdowns)]; //creates new points array

Comments:

Ad: