Split a string into chunks at every odd and even index

I have limited knowledge of javascript.

When given the string "3005600008000", I need to devise a method that multiplies all the digits in the odd-numbered positions by 2 and those in the even-numbered positions by 1.

This code snippet I drafted seems to output TRUE for the odd numbers (e.g., "0"),

var camid;
var LN= camid.length;
var mychar = camid.charAt(LN%2);

var arr = new Array(camid);
for(var i=0; i<arr.length; i++) {
    var value = arr[i]%2;
    Alert(i =" "+value);
}

However, I suspect it does not effectively group/split the string at odd (and eventually even) positions.

How can this be accomplished? Any hints would be appreciated.

/=================================================/

The objective is to create a validation routine on a webpage for a smartcard ID number.

The process I aim to implement is as follows:

· 1) Begin from the left side, multiply the digits in the odd-numbered positions by 2 and those in the even-numbered positions by 1.

· 2) In case a single digit multiplied by 2 results in a two-digit number (like "7 x 2 = 14"), sum the resulting digits to obtain a new single-digit outcome ("1+4=5").

· 3) Aggregate all single-digit outcomes.

· 4) The check digit is the amount needed to add to the sum obtained in step #3 to reach the next highest multiple of ten. For instance, if the total in step #3 is 22, adding 8 to 22 will get you to the next highest multiple of 10 (30). Therefore, the check digit is 8.

That's the gist of it. Researching about smartcard ID validation using Google did not return any useful results, leading me to question whether implementing this in Javascript is overly complicated...

Any suggestions are welcome.

Answer №1

var numberArray = id.split(''); // creating an array entry for each digit in the ID
var count = numberArray.length, index, value;
for(index = 0; index < count; index++) { // looping through each digit
  value = parseInt(numberArray[index], 10); // checking if each string digit is an integer
  if(!isNaN(value)) {
    alert((value % 2) ? value * 2 : value); // multiplying the value by 2 if it's an odd number, otherwise outputting the value itself
  }
}

Answer №2

After some research, I stumbled upon the term Luhn validation to describe what I'm attempting to achieve.

Luckily, I came across an algorithm that fits my needs perfectly.

http://example.com/luhn-validation-algorithm

I really appreciate your assistance in guiding me towards the right solution. Thank you!

Answer №3

It seems that you are working on a Luhn validation process. Remember, when counting odd/even digits, start from the RIGHT side of the string, not the left.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for increasing visibility for your Google Analytics Embed API Custom Components

I recently tried to incorporate some code I found at the following link: After downloading the files view-selector2 and date-range-selector, I saved them in my local directory. I made a modification to the code: var accountSummaries = require(['&ap ...

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

Using the "this" keyword in JavaScript to access the "rel"

Take a look at the JSFIDDLE , where you will notice that the rel attribute in the alert is shown as 'undefined' : var ItemTypeArray = $('input[name^=ItemType]:checked').map(function(){ alert(this.id + ' , r= ' + this.rel) ...

How can we display the data returned by a successful AJAX request

Having an issue with displaying Ajax success data. success: function(data){ alert(need to print it here); } When I try to access the data using: console.log(data.responseText); {"success":false,"errors":{"text":["Some text.","some more text"]}} Any ...

Using JavaScript to dynamically calculate the sum of selected column values in Angular Datatables

I have a table set up where, if a checkbox is checked, the amounts are automatically summed and displayed at the top. However, I am encountering issues with the code below as it is not providing the exact sum values. Can anyone suggest a solution to this p ...

The IntroJs step is only partially visible on the screen

Currently, I am incorporating introJS into my application and encountering an issue where one of the steps is only partially visible on the screen. Despite trying various position settings such as auto, left, right, etc., this particular item consistentl ...

Angular sing ng-view to load images from a file

I am developing a single page app (index.html) with the following relevant sections: <!DOCTYPE html> <html> <head> <base href="/mi_ui/"> <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css"> <script s ...

Interactive element for initiating a HTTP request to NodeJS/Express server to trigger a specific function

I currently have a frontend button implemented using nodejs and express for my server-side backend. The button is supposed to trigger a function that controls the Philips Hue API on the backend via an HTTP request. I have experimented with various approac ...

Sending AJAX information to multiple pages

I have created an HTML page where I am struggling to pass two variables using the POST method to a PHP page. The PHP page is supposed to accept these variables and then call an API to retrieve data based on them. However, my challenge is in receiving this ...

When creating routes in Express 4.* using node.js, it is essential to use the root directory

Completely new to the world of node.js, I find myself navigating through an outdated and partially functioning course on udemy.com. In previous modules, I managed to successfully receive content through routes like app.get('/vegetables',functio ...

Having trouble getting an HTML form to function with Ajax and PHP?

Seeking assistance from anyone who can lend a hand. I am delving into the complexities of Ajax, and I'm encountering issues where it seems like the script is being completely ignored or perhaps I'm just making a rookie mistake. Prior to display ...

How should dynamic route pages be properly managed in NextJS?

Working on my first project using NextJS, I'm curious about the proper approach to managing dynamic routing. I've set up a http://localhost:3000/trips route that shows a page with a list of cards representing different "trips": https://i.stack. ...

The altered variable refuses to show up

Currently, I am working on a project to create a Skate Dice program that will select random numbers and display the results simultaneously. Unfortunately, I have encountered an issue where the randomly generated number is not being shown; instead, it dis ...

What is the best way to convert a Date into the JSON format before sending it to the database?

I'm currently delving into backend development with Node.js, and I am in the process of connecting my backend to a MongoDB. Specifically, I am working on creating a User object that includes Birth Date as one of its properties. However, I am strugglin ...

Preventing memory leaks by harnessing the power of Node Streams and promises

I am trying to wrap node streams in an async function, but I'm concerned about potential memory leaks in the following code. Will readStream and result be properly garbage collected after the promise is resolved or rejected? If not, what steps can I t ...

Using a Vue computed property updates the values within the data object

My data structure (this.terms) looks like this: { name: 'First Category', posts: [ { name: 'Jim James', tags: [ 'nice', 'friendly' ] }, ...

Using a semicolon at the end of the line is considered a favorable practice when writing ES6 code in Babel

After browsing through various tutorials on the internet that utilize redux and react, I came across a common trend of omitting semicolons in ES6 code when using Babel. For instance, some examples neglect to include semicolons at the end of import or expo ...

Having trouble adding state values to an object

I have a specific state set up in my class: this.state = { inputValue: "", todos: [] } My issue lies within an arrow function where I am attempting to use setState to transfer the value of inputValue into todos. this.setState({ inputValue: & ...

Is it possible to determine if a variable is unset using isset?

Currently, I am utilizing the following code snippet to verify if isset is not set. For instance: if(!isset($_REQUEST['search'])) { } else if(!isset($_REQUEST['submit'])) {} I would like clarification on whether !isset is considered ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...