What is the most effective method for transforming array A into array B?

Is there a more efficient way to manipulate array A to get array B, considering the given variable "k"? I have come up with the following logic but believe there may be a better approach.

The length of the array is always divisible by k

This part is not the code. It doesn't let me submit it otherwise.
k=3
Given: A = [0,1,2,3,4,5,6,7,8,9,10,11] 

Result: B = [9,10,11,6,7,8,3,4,5,0,1,2]

k = 4
Given: A = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Result: B = [12,13,14,15,8,9,10,11,4,5,6,7,0,1,2,3]

The number of elements in A changes when k changes. The number of elements for A is always k*4. For example, if k is 2, our A array would be [0,1,2,3,4,5,6,7], and the resulting B array should be B = [6,7,4,5,2,3,0,1]

let A = [0,1,2,3,4,5,6,7,8,9,10,11]
k = 3
let B = []

    for (let i=A.length - (k-1); i >=0; i=i-k) {
        if (A.length - 1 <= i + k +1) {
            B = [
                ...B,
                ...(A.slice(i+1, i+k+1))
            ]
        }
    }
    B = [
        ...B,
        ...(A.slice(0,k))
    ]

Answer №1

Here is a simple solution:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let chunkSize = 2

const chunks = []
for (let i = numbers.length; i > 0; i -= chunkSize) {
    chunks.push(...numbers.slice(i - chunkSize, i))
}

Answer №2

Is this the solution you are looking for?

const array=[0,1,2,3,4,5,6,7,8,9,10,11];

function rearrange(array, size){
  for (var result=[], index=size*~~array.length/size; index>0 ; index-=size)
    result=result.concat(array.slice(Math.max(index-size,0),index));
  
  // Alternatively:
  for (var subArray=[], index=array.length-size; index>-size ; index-=size)
    subArray=subArray.concat(array.slice(Math.max(index,0),index+size));
  
  console.log("Size:"+size+"\nVersion one: "+result+"\nVersion two: "+subArray)
}

for (let num=1; num<12; num++) rearrange(array,num)

I adjusted your code by testing different values of size from 1 to 11. It was unclear what should happen if the array's length is not perfectly divisible by size. My assumption was to create full-length groups followed by a smaller last group with only two elements.

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

Confirming delete with jQuery and AJAX

Before sending an AJAX request to remove an item from the database, I require an OK/Cancel delete confirmation dialog box. var id=ID; $.ajax({ type: "POST", url: "sample.aspx?Mode=Delete", data: { id: id }, success: function (response) ...

The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is di ...

Using Angular's $post method to communicate with PHP CodeIgniter for making requests and handling responses

I am having trouble sending data from Angular to Codeigniter using $post. Here is the JavaScript code I am using: $scope.user.first_name = 'first name'; $scope.user.last_name = 'last name'; $http({ method: 'POST', ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...

React - A guide on accessing the scroll position of a div using JavaScript

Within my side navigation bar, there is a title and other information. The title is fixed in place (sticky) and the sidebar has a height of 100vh. I am looking to add a box-shadow effect to the title div (sticky-title) only when the user scrolls down past ...

Exploring the functionalities of the componentDidUpdate() method in React JS

In my project, I am trying to dynamically change an API parameter using a click function and render new data accordingly. The issue I encountered is that when I trigger the componentDidUpdate method with an onclick event listener, the first click works fin ...

Is it possible to adjust table rows to match the height of the tallest row in the table?

I've been attempting to ensure that all table rows have the same height as the tallest element, without using a fixed value. Setting the height to auto results in each row having different heights, and specifying a fixed value is not ideal because the ...

JAVASCRIPT ENCOUNTERS ISSUE WITH RANDOM TEXT GENERATION

Utilizing an array of words, we are in the process of generating random text. The goal is to shuffle and combine these words to form new "random sentences". However, we have encountered a minor issue - the addition of "undefined" at the beginning of each p ...

Animating objects in ThreeJS to traverse multiple positions smoothly with linear interpolation (lerp)

I am exploring ways to animate a sphere's movement along a predefined sequence of vertices. I have successfully managed to animate the sphere from one point to another using the code below: function animate() { requestAnimationFrame(animate) spher ...

Transform the hue of symbols within D3-legend

I am attempting to modify the appearance of symbols in a legend. The variable below represents the available symbol types: var symbolTypes = { "triangleUp": d3.svg.symbol().type("triangle-up"), "circle": d3.svg.symbol().type("circle") }; I use this varia ...

Guidelines for choosing AngularJS checkboxes to exclusively choose distinct matching items

Need help with selecting common items using Angular checkboxes. Below is the mock UI-Table: Order Id | Delivery Mode | Select 1 | Speed | ::checkbox:: 2 | Normal | ::checkbox:: 3 | Contractor | ::che ...

Implementing React router for dynamic page rendering

I'm struggling to make sense of a particular piece of code. Can someone provide an explanation? I'm particularly confused about the role of "props" in this section and how it is essential for the code to work correctly. If I remove "props," my co ...

Retrieve the information from the recently completed request

When the user inputs 'id' into the text field, I want to fetch a post based on the specific id entered by the user. If no id is provided, I would like to fetch the entire array of posts and then retrieve an id from the fetched data for testing pu ...

Tips for sending an email without using MAILTO in JavaScript or jQuery

Today is a great day for many, but unfortunately not for me. I've been struggling with this issue for over two weeks now and can't seem to find a solution anywhere on the internet. Stack Overflow always comes to my rescue when things get really t ...

Unable to save cookies using AngularJs

Currently, I am immersed in a small project utilizing AngularJs. The main objective of this project is to save a user's username and password within browser cookies. Here is my snippet from app.js where you can observe ngCookies being injected as a d ...

Activate the Vue checkbox option

Starting out with Vue and web development. I am currently building my app using Laravel and Vue. This is the code snippet I am working on: created: function () { let self = this; self.setActive('tab1'); axios.get(this.$apiAdress + '/api/tas ...

Tips for modifying the function of an Electron application using an external JavaScript file

This is the project structure I envision. https://i.stack.imgur.com/ocRp9.jpg kareljs folder houses an Electron app, and upon running npm start within that directory, a window appears and executes the run method of karel.js when the button Run Karel is ...

Failure of Chrome to automatically mark checkboxes as checked upon page loading

When a user clicks on checkboxes on my page, an ajax call is made to the server with form data from the checkboxes to filter the list. However, all settings are lost when the user navigates to another page. To retain checkbox form data, I want to store it ...

What is the best way to make changes to elements in an express array?

I have been developing an express application that enables users to manage a list of web projects through various HTTP methods such as get, post, put, and delete. So far, I have successfully implemented the logic for handling get, delete, and post reques ...

Error Message: Stencil Launch Issue - InvalidTypeException("The parameter 'url' should be in string format, not " + the data type of url)

I have been working with stencil for quite some time now and am in the process of developing a custom theme for it. I have installed nvm, node 5.0, and npm 2. Despite deleting stencil and doing a fresh install of everything, including node modules and st ...