Obtain a specific amount of values from arrayA[5000] and transfer them into arrayB[] grouped together

My array looks like this:

 arrayA = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2];

I want to organize the numbers into groups like this:

arrayB = [1234,5678,9123,4567,8912];

Essentially, I need to take the values from arrayA and create new numbers by grouping 4 numbers together.

My current code has a bug where the output looks like this:

arrayB=[undefined1234,undefined5678];
This is the code I used:

for (var i = 0; i < 20; i++) {
        if (i/4== n+1){
            arrayB[n] = temp;
            n++;
        }
         temp += arrayA[i];
}

I recognize that the bug is due to the += operator, but I'm unsure how to resolve it.

Answer №1

By utilizing this script, you can achieve the desired outcome

        var numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120];
        var updatedNumbers = [];
        for (var i = 0; i < numbers.length; i += 5) {
           updatedNumbers.push(numbers.slice(i, i + 5).join(''));
        }

        console.log(updatedNumbers);  

Additional Information
After receiving a suggestion from Mike, it's now recommended to include the following code in the for loop for numerical values in the result array

updatedNumbers.push(parseInt(numbers.slice(i, i + 5).join('')));

Answer №2

Consider initializing the variable temp as an empty string before the loop begins, and reinitialize it as an empty string each time you assign a value to the variable arrayB (ensuring to convert the string in the variable step to an integer). Additionally, you may need to make a final assignment to the variable arrayB after the completion of the for loop.

Answer №3

This is my approach:

numArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2];
tempString = numArray.join('');

groupSize = 4;

groupedNums = [];

maxIndex = tempString.length / groupSize;

for (j = 0; j < maxIndex; j++) {

  groupedNums.push(parseInt(tempString.substr(j * 4, 4)));

}

console.log(groupedNums);

Simple conversion from numbers to strings and then back to numbers. :) Check out the demo here: http://jsfiddle.net/hue0a1wb/

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

Utilizing Node as an intermediary to transmit form-data to a Java server

I am working on an application that utilizes axios for communication with a node server, which then interacts with a separate java server. Calling the node server from the client: // assuming payload is of type FormData() axios.post(url, payload).then((r ...

Steps for generating a dropdown menu using API JSON information

I'm new to using Webapi with AngularJS. I have a URL that returns data in JSON format, and I want to extract only the employee names from the data and display them in a dropdown list using AngularJS. Any assistance would be greatly appreciated. ...

The regular expression should consist of just letters and a single dot

Currently, I am working on creating a regular expression that allows only letters and one dot. However, there is a specific rule to follow: the dot cannot be located at the beginning or end of the string. For example: abc.difference This is what I attem ...

Utilize JavaScript to Replace KeyPress Event on Input Field

While attempting to substitute the key press of "K" with "Z" in an input field, I managed to accomplish it successfully. However, there seems to be a slight delay that causes the user to observe the transition from "K" to "Z". Below is the code that I use ...

The issue with AngularJS Routing is that it fails to refresh the menu items when the URL and views are being

My current project involves implementing token-based authentication using the MEAN stack. The goal of my application is to display different menu items based on whether a user is logged in or not. When there is no token present, the menu should show option ...

What is the reason behind the absence of unwrapping when utilizing a ref as an element within a reactive array or reactive Map?

The Vue documentation states the following: Unlike reactive objects, there is no unwrapping performed when the ref is accessed as an element of a reactive array or a native collection type like Map Here are some examples provided in the documentation: c ...

The Final Div Fluttering in the Midst of a jQuery Hover Effect

Check out my code snippet here: http://jsfiddle.net/ZspZT/ The issue I'm facing is that the fourth div block in my example is flickering quite noticeably, especially when hovering over it. The problem also occurs occasionally with the other divs. Ap ...

Issues with sending data through ajax using the post method persist on shared web hosting

I'm facing an issue with Ajax post data. It works fine on localhost but not on shared hosting. Here is my code: <script type="text/javascript> $(document).ready(function(){ $("#login").click(function(){ alert(& ...

What is the process for triggering an event to initiate an action within a Node server or a websockets loop?

I'm currently delving into the realm of websockets using Node.js ws and Node mplayer in order to tackle a specific issue. At the moment, I have a straightforward websocket (ws) loop set up along with a fully operational mplayer instance. I am able to ...

Is the security of Angular's REST authentication reliable?

My goal is to establish a secure connection with a REST service using Angular. I have come across the official method, which involves setting the authentication ticket like this: $httpProvider.defaults.headers.common['Authorization'] = 'dhf ...

The issue with the error handler middleware is that it is failing to effectively manage and resolve

Recently, I started utilizing this npm package as a workaround for try-catch blocks and promises. However, it seems like the error handler is consistently inactive. Does anyone have any insights on where I might have gone wrong in this scenario? When I enc ...

Utilize Vue to access and read a file stored in the current directory

I am attempting to retrieve data from a text file that is located in the same directory as my .vue file. Unfortunately, I am encountering an issue where the content of the text file is not being displayed in both Chrome and Firefox. Instead, I am seeing th ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

Attempting to transmit a text message to a PHP script using Ajax

Hey there! I'm facing a challenge while trying to send a string to a PHP file using AJAX. It seems like the http.send function is not working as expected, and I suspect there might be an issue in my code. (I'm fairly new to programming) mainlin ...

Issue with Angular ui-select causing repeated $http requests in ui-select-choices

I'm currently working on integrating ui-select into my project, and this time I need to pass a controller function as options to ui-select-choices. Here's how it's set up: HTML: <ui-select ng-model="selectedItem" theme="selectize" ng-di ...

Error message '[object Error]' is being returned by jQuery ajax

I'm currently facing a challenge with my HTML page that calls an API. Every time I attempt to run it, I encounter an [object Error] message. Below is the code snippet in question: jQuery.support.cors = true; jQuery.ajax({ type: "POST", url: ...

The duration spent on a website using AJAX technology

We conducted an online survey and need to accurately calculate the time spent by participants. After using JavaScript and PHP, we found that the calculated time is not completely accurate. The original script was sending server requests every 5 seconds to ...

An issue arises when request.body appears blank within the context of node.js, express, and body

I am currently attempting to send a request to my node server. Below is the xhttp request being made. let parcel = { userId: userId, //string unitid: unitid, //string selections: selections //array }; // Making a Call to the Server using XMLHttpR ...

I am feeling quite lost in trying to figure out how to create a voice mute command using Discord

I've been searching for information on how to create a command that mutes only one specific person I tag in chat, but I'm having trouble finding any guidance on it. As someone new to discord and node js, I could really use some assistance. Mute ...

Mapping Services API for Postal Code Borders by Google

After hitting a dead end with Google Maps Marker, I am seeking help to replicate the functionality for users on my website. Specifically, I want to take a user's postal code and outline their boundaries using Google Maps API. If anyone has knowledge o ...