Step 11
The next stage of the Luhn algorithm involves summing up the digits (elements of our array from the previous step) in various ways. Eventually, we want to reduce the array (digits in a card number) to a single value. The array's reduce
method can be used here. To understand how it works, we first add up all the array elements:
const cnumber = "4003600000000014"; let arr = cnumber .split('') .reverse() .map(element => parseInt(element)); const sum = arr.reduce(reducer, 0) function reducer(accumulator, currentValue) { return accumulator + currentValue; } console.log(sum);
The reduce()
method executes a user-supplied “reducer” function on each element of the array. A "reducer" function can take four arguments:
accumulator
(the value resulting from the previous call to reducer)currentValue
(the value of the current element)currentIndex
(the index of the current element) Optionalarray
(the array to traverse) Optional
Notice the second argument to the reduce
method is the initial value for the accumulator
.
We can provide the reducer in-place as an arrow function:
const cnumber = "4003600000000014"; let arr = cnumber .split('') .reverse() .map(element => parseInt(element)); const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum);
In the next step, we will finalize Luhn's algorithm.