JavaScript: Implement the Luhn Algorithm used to validate a variety of identification numbers
JavaScript fundamental (ES6 Syntax): Exercise-80 with Solution
Write a JavaScript program to implement the Luhn Algorithm used to validate identification numbers. For example, credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
- Use String.prototype.split(''), Array.prototype.reverse() and Array.prototype.map() in combination with parseInt() to obtain an array of digits.
- Use Array.prototype.splice(0, 1) to obtain the last digit.
- Use Array.prototype.reduce() to implement the Luhn Algorithm.
- Return true if sum is divisible by 10, false otherwise.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const luhnCheck = num => {
let arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0);
sum += lastDigit;
return sum % 10 === 0;
};
console.log(luhnCheck('4485275742308327'));
console.log(luhnCheck(6011329933655299));
console.log(luhnCheck(123456789));
Sample Output:
true false false
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-80-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to take any number of iterable objects or objects with a length property and returns the longest one.
Next: Write a JavaScript program to create an object with keys generated by running the provided function for each key and the same values as the provided object.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join