Array Methods

A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.


Here is a sample array of credit card numbers:

['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978', '4556-4242-9283-2260']

In the sample array above, the digits add up to 49, 81, 81, and 64 respectively. Since there are two which have the same sum, the function should return the last one with that sum, in this case '4252-278893-7978' Things to accomplish:

Historical Answer:

I am not quite sure just what this question is intended to test for when an historical solution is given and I am not even going to give the code for the historical version. To solve this historically would involve numerous for loops and if you know how to code a for loop then coding four or five of them isn't really testing anything more than coding one.

This homework question makes way more sense as a modern JavaScript question because then it is actually testing for knowledge of the various array methods - in this case map(), reduce() and filter() all contribute to obtaining the solution.

JavaScript Answer:

var arr = ['4916-2600-1804-0530', '4779-252888-3972',
 '4252-278893-7978', '4556-4242-9283-2260'];

var findMax = function(arr) {
  var t = {return x.split('').reduce(
     function(b,c){return +c ? +b+(+c) : b;},0);});
  var m = Math.max.apply(null,t);
  return arr.filter(function(d,e) {return t[e]==m},t);


The assignment to 't' adds the digits for each of the credit card numbers skipping the dashes giving us an array of the totals and the assignment to 'm' gets the highest number from that array. The return then passes back an array of all of the entries from the original array where the sum of the digits is equal to the maximum value. We pop the last entry off that array to give the last entry that meets the criteria.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow