DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
What's in store for DevOps in 2023? Hear from the experts in our "DZone 2023 Preview: DevOps Edition" on Fri, Jan 27!
Save your seat
  1. DZone
  2. Data Engineering
  3. Data
  4. Sequences using JavaScript Array

Sequences using JavaScript Array

Ariya Hidayat user avatar by
Ariya Hidayat
·
Jul. 24, 13 · Interview
Like (1)
Save
Tweet
Share
8.22K Views

Join the DZone community and get the full member experience.

Join For Free
numbers

generating a sequence is a common programming task. this is rather easy to achieve using a straightforward loop. with javascript however, there exists a more functional variant using the powerful array object. this permits the generation of all kind of sequences, from a..z to a list of prime numbers, without any loops at all.

supposed you are about to create a list of numbers 1, 2, 3 and place it in an array, one possible loop-based implementation is:

var result = [];
for (var i = 1; i != 4; ++i) result.push(i)
console.log(result);  // [1, 2, 3]

obviously, tweaking the code can yield a different kind of sequence. for example, a sequence of latin alphabets is a matter of converting each number into the right letter:

var list = '';
for (var i = 0; i != 26; ++i) list += string.fromcharcode(i + 65);
console.log(list);   // 'abcdefghijklmnopqrstuvwxyz'

using loops is nice, but can we get the same result sans loops ? fortunately, javascript is quite capable of doing it. we just need to rely on its built-in object array . in the following explanation, all the sections mentioned refer to the standard ecma-262 , the official ecmascript language specification edition 5.1.

earth

first of all, we need to create an array which has the specified amount of elements. for that 1,2,3 example, we need a 3-element array. fortunately, this is trivial:

array(3);

note that there is no need to use new for object construction, this is explained in section 15.4.1 :

when array is called as a function rather than as a constructor, it creates and initialises a new array object.

array(3) creates an array with the length of 3, it is the same as [,,,] . the resulting array however has holes in it. in fact, although it has 3 elements, those elements do not exist. holes like this are not so obvious if you try to peek at the array contents. compare the two lines:

array(3).join('-');                // "--"
[null,undefined,null].join('-');   // "--"

we can verify the existence of an array element just like checking for a property in a generic javascript object, using the in operator (section 11.8.7 ):

0 in array(3);   // false
1 in array(3);   // false
2 in array(3);   // false
2 in [,,9];      // true

as pointed by axel rauschmayer, holes inside an array are also detected with foreach .

water

how to fill those holes? a trick discovered by many seasoned javascript developers (see e.g. brandon benvie’s post on es-discuss) is to use array.apply . instead of some empty elements, now we have undefined to replace them:

array(3);                  // [,,,]
array.apply(0, array(3));  // [undefined, undefined, undefined]

to really understand this trick, recall how function.prototype.apply works (section 15.3.4.3 ), particularly in the step 8, transforming an array into an argument list for the function, called spreading . no wonder this approach is quite often used to find the minimum or maximum value in an array. in the following fragment, the two lines are identical:

math.max(14, 3, 77);                 // 77
math.max.apply(math, [14, 3, 77]);   // 77

when apply receives an array with an empty element, it gets converted into undefined and thereby eliminates any holes in the array. if we combined it with array construction, the end effect is constructing a new array with the spread.

array.apply(0, [1,,3]);  // is the same as
array(1, undefined, 3);

air

now that we have an array with the right number of elements, how do fill it with the right sequence? array.prototype.map to the rescue! section 15.4.4.19 shows that:

map calls callbackfn once for each element in the array, in ascending order, and constructs a new array from the results.

further down, we also observe that:

callbackfn should be a function that accepts three arguments. callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.

the second argument, the index of the element, is the key to our solution:

array.apply(0, array(3)).map(function (x, y) { return y + 1; });  // [1, 2, 3]

and if the sequence is about the squares of the first few integers:

array.apply(0, array(3)).map(function (x, y) { return (y + 1) * (y + 1); });

finally, for the english alphabets ‘abcdefghijklmnopqrstuvwxyz’:

array.apply(0, array(26)).map(function(x,y) {
  return string.fromcharcode(y + 65);
}).join('');

for alternatives to using map , see also brandon benvie’s usage of function.call with number or ben alman’s solution with object.keys .

fire

with the new array comprehension feature of the forthcoming ecmascript 6, the above one-liners can be slightly tweaked. for example, the alphabets sequence might be written as (note the use of arrow function ):

[for (i of array.apply(0, array(26)).map((x, y) => y))
string.fromcharcode(65 + i)].join('');

here the conversion from each number to the corresponding letter is carried out outside the map callback. this makes the code easier to digest, it resembles a proper composition: generate the sequence first and do another step to transform the sequence. for details, check out my previous blog post (with tons of examples) on ecmascript 6 and array comprehension.

loops are overrated, aren’t they?

related posts:

  • ecmascript 6 and spread operator
  • ecmascript 6 and array comprehension
Data structure JavaScript Element

Published at DZone with permission of Ariya Hidayat, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Essential Mobile App Security Tips for Coders in 2023: Make Your App Unhackable
  • Core Machine Learning Metrics
  • Load Balancing Pattern
  • Hugging Face Text Classification Tutorial Using PyTorch

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: