Combining string values by utilizing functions and loops and saving them into an array

Looking to split a string of numbers into different variables within an array. The first variable needs to be 3 characters long, the six in the middle should be 7 characters long, and the last one should have a length of 3. Any suggestions on how I can achieve this using functions and loops?

Answer №1

We have the following code snippet that demonstrates a way to achieve our goal:

 
let str = '000111111122222223333333444444455555556666666mmmm';

// Setting up the lengths we are working with
let lengths = [3,7,7,7,7,7,7,3];

let index = 0;

let result = lengths.reduce((acc,n) => {
    acc.push(str.slice(index, index += n));
    return acc;
} , [])

console.log(result);

Answer №2

One way to approach this problem is by breaking down the string into substrings.

let text = '000111111122222223333333444444455555556666666mmmm',
    lengths = [3, 7, 7, 7, 7, 7, 7, 3],
    result = lengths.map((i => l => text.slice(i, i += l))(0));

console.log(result);

Answer №3

Below is a simple approach to achieve the desired outcome:

const arrayElement = document.getElementById('arrayElement');
const variableElement = document.getElementById('variableElement');
const targetString = "122333444455555666666";
const dataSizes = [1, 2, 3, 4, 5, 6];
let result = [];
let position = 0;
dataSizes.forEach( (size) => {
    result.push(targetString.substr(position, size));
    position += size;
});
arrayElement.textContent = result.toString();
const [one, two, three, four, five, six] = result;
variableElement.textContent = `${one}-${two}-${three}-${four}-${five}-${six}`;

Answer №4

To accomplish this task in a simple manner, you can store the desired substring lengths in an object and then extract those substrings from a given string:

let str = "abcdefghijklmnopqrstu";
let subStringLengthMap = {a: 3, b: 7, c: 7 , d: 3};

//creating a pure function
var getStrings = function(str, subStringLengthMap){
  let result = [];
  Object.keys(subStringLengthMap).forEach(function(key){
    let temp = str.slice(0, subStringLengthMap[key]);
    result.push(temp);
    str = str.replace(temp,'');
  })

  return result;
}

//invoke the function
console.log(getStrings(str, subStringLengthMap))

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

Click on the tooltip to make it disappear

Is there a way to automatically hide the tooltip after clicking on the dropdown menu? Here is the JavaScript snippet: <script type="text/javascript"> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip({ placement : &a ...

Why is the JavaScript function working even without any arguments?

During my search for some JS Code, I stumbled upon this piece of code. Check out the code snippet below: arg = "TEST ALERT MESSAGE"; MyFunction(arg); function MyFunction() { alert(arg) } In the above code snippet, the MyFunction() is provided with an a ...

Interacting between front-end inline JavaScript and back-end Node.js

I am currently working with Node.js and I need to send a request to the server with an input value when a button is clicked. Here's the HTML code I have: <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

I am having trouble correctly dereferencing an array

Although my Perl skills are not as advanced as I'd like, I am determined to figure out how to sort a multi-dimensional array. I've been experimenting with some test code to better understand the concept, and while I feel like I'm making prog ...

Troubleshooting problems with Angular JS $http configuration involving withCredentials and the wildcard character in Access-Control-Allow-Origin

I'm currently developing a mobile app using Ionic and Angular. I've been facing an error in my code for the past few hours: function PromiseCtrl($scope, $http) { $http({ method:'GET', url:"http://www.omd ...

Inspecting the session array to identify a specific value

function CHECKITEMEXIST($cartarray, $sub){ foreach ($cartarray as $item){ foreach ($item as $item2){ if($item2['subject'] = $sub){ return '1'; }else{ return '0&ap ...

Tips for minimizing a collection of objects?

Currently, I am working on developing a unique quiz format where there are no correct or incorrect answers; instead, responses are given a score ranging from 1 to 4. Each question falls under one of four distinct categories (such as cat, dog, rabbit, alpa ...

What is the best way to showcase arrays in a JSON document?

I'm working on a basic AJAX code to show a JSON file stored locally using this HTML, but I keep getting an 'undefined' error. I'm opting for JavaScript instead of JQuery since I haven't delved into it yet; hoping my code is syntact ...

Should I consolidate my ajax requests into groups, or should I send each request individually?

Currently working on an ajax project and feeling a bit confused. I have 3 functions that send data to the server, each with its own specific job. Wondering if it's more efficient to group all the ajax requests from these functions into one big reques ...

Preserving the scope value when refreshing the page from the cookie storage

One of my controllers has the code below: $scope.artistId = $cookies.artistId; $scope.artistName = $cookies.artistName; $scope.switchArtist = function(artist) { $scope.artistName = ''; $scope.artistId = ''; $scope.arti ...

Easier JavaScript for numerous HTML elements

I am an aspiring JavaScript learner seeking advice. Currently, I am working on a website that features numerous items with multiple images for each. I am utilizing JQuery to display a larger image when the user hovers over a thumbnail image. My query is ...

Step by step guide on enabling link routing on a Material UI list item, excluding only one specific button within the list item

I am facing an issue with a component containing ListItem components from material ui. Each ListItem has a button, and the entire listitem should be clickable to route the app somewhere. However, when clicking the delete button, it also routes the app to ...

Arranging an array of changing elements within a structure using C's qsort() function

I am facing an issue with sorting an array that is dynamically allocated inside a structure. Initially, the plan was to arrange the array i in the structure in ascending order. Then I considered organizing the array i while maintaining the relationship w ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

Is the JavaScript code not executing properly?

There seems to be an issue with this code as it's not displaying an unordered list of HTML elements as intended. I've written the script and HTML code using Sublime Text, but even after trying to run the script in Chrome's developer console ...

Execute JavaScript after authentication instead of forwarding the user to another page

Short version: How can we efficiently handle a second AJAX call after an ASP.NET Membership Authentication response? Long version: Let's say we have a web-based Paint program created using ASP.NET MVC. A user is painting a picture when suddenly their ...

Creating a responsive image within a panel using Bootstrap

I've been struggling to make a responsive image fit inside a panel while maintaining its aspect ratio and ensuring none of it gets cut off. I've attempted various CSS tweaks with no success. My setup involves Bootstrap along with React.js using r ...

Select a JSON item at random using PHP

After analyzing a JSON string, it was discovered to contain various items with different formats and content. Here is an example: [{"Format":"I25","Content":"172284201241"}, {"Format":"I25","Content":"40124139"}, {"Format":"I25","Content":"20197086185689 ...

Web application for muting and kicking users in a channel using ARI

I am currently facing a situation where two functions are triggered automatically when I add a call to a bridge. To manage this, I am trying to utilize JQuery so that these functions only execute when a specific button is clicked. This will allow me to pro ...

Converting SHA-256 from Java to JavaScript in an Ionic project using NPM: A step-by-step guide

In Java, I have a code snippet that needs to be converted into JavaScript using the Ionic Framework. I attempted to use Ionic App along with NPM packages like "crypto-js" and "js-sha256", but I was unable to find a suitable solution. String generate ...