Combine multiple arrays into a single array by utilizing a for loop

In my lab assignment, I was given an array of names like this:

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

The task is to write a function that will create an array containing subarrays with three names each:

`[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]`

I attempted it and ended up with one flat array as follows:

function sortByGroups() {
    let arr = [];
    for (let i = 0; i < names.length; i = i + 3){
        for (let j = i; j < i + 3; j++){
            if (j < i + 2){
                arr += `${names[j]},`;
            } else {
                arr += `${names[j]}`;
            }
        }
        return arr.split(',')
    }
}
console.log(sortByGroups()); // [ 'Peter', 'Andrew', 'Ann' ]

However, I am stuck on how to further manipulate the data to achieve the desired output:

[['Peter', 'Andrew', 'Ann'], ['Mark', 'Josh', 'Sandra'], ['Cris', 'Bernard', 'Takesi']]

Answer №1

Given a set of integers represented as i=0,1,2, you can extract elements from 3i to 3i+2

One way to achieve this is using a for-loop:

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const groupedNames = []
for(let j=0; j<Math.ceil(names.length); j+=3){
groupedNames.push(names.slice(j,j+3))
}
console.log(groupedNames)

An alternative approach could be...

This method first generates the list of integers and then organizes the entries accordingly.

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];

const groupedNames = Array(Math.ceil(names.length/3)).fill(0).map((_,i)=>names.slice(3*i,3*(i+1)))

console.log(groupedNames)

Answer №2

  • Iterating through each name in the list, we use a temporary variable lastUsedIndex to keep track of the last element added to a group. We ensure that the current index is greater than the lastUserIndex.
  • It's important to note that if there is an extra element in the source data, it will form a group with
    ['that data',undefined,undefined]
    .

const names = ['Peter', 'Andrew', 'Ann', 'Mark', 'Josh', 'Sandra', 'Cris', 'Bernard', 'Takesi'];
let lastUsedIndex = -1;
const groupedNames = [];
names.forEach((name, i) => {
  if (i > lastUsedIndex) {
    lastUsedIndex = i + 2;
    groupedNames.push([names[i], names[i + 1], names[i + 2]]);
  }
})

console.log(groupedNames);

Answer №3

You can utilize the Array.reduce method to loop through the array and return the resulting array.

const firstNames = ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank'];

const groupNames = (num) => firstNames.reduce((previous, current, index) => {
    let arrIndex = Math.floor(index / num);
    previous[arrIndex] = [...(previous[arrIndex] || []), current];
  return previous;
}, []);

console.log(groupNames(2));

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

AJAX, JQuery, JQuery UI, CSS, and custom JavaScript are experiencing loading issues

Can anyone explain why my AJAX requests only work when I remove //code.jquery.com/jquery-1.9.1.js from my site, but then I can't access the JQuery UI datePicker? <head> <link rel="stylesheet" type="text/css" href="CSS/custom.css"> < ...

Creating a tooltip with a left arrow and a bordered design

I am looking to create a tooltip that displays its content after clicking on the tooltip tip icon. Currently, it only works on hover, but I want it to be clickable and mobile responsive. Desktop design should resemble: https://i.sstatic.net/FQPyt.png Mob ...

The jQuery target is not able to locate the specified element

Why does this code snippet work in one case: jQuery(this).closest("li").find("p").text(); But when enclosed within a function, it fails to produce the desired result: jQuery.each(words, function(i, v) { jQuery(this).closest("li").find("p").text(); } ...

Is it possible to upload numerous profiles into the MYSQL database using this WP template?

Apologies in advance if my question is unclear, but in simple terms, I am looking to automate the process of uploading hundreds of profiles and jobs to this WP template: The developer of this template has stated that it is not possible to do this through ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

Working with AngularJS to Create Repeated Divs and Buttons

Currently, I'm looking to utilize ng-repeat to iterate over a div that contains a button. At the moment, I am achieving this by generating the div and button in the JavaScript section and then adding the final outcome to an array: var newDiv = docum ...

Using Vue to dynamically wrap a component with a tag

Have you ever wondered how the v-if directive in Vue.js can hide an entire component along with its content based on a condition? I am curious to know: Is it possible to only hide the surrounding tag or component without removing its contents? ...

The 'palette' property is not found on the Type 'Theme' within the MUI Property

Having some trouble with MUI and TypeScript. I keep encountering this error message: Property 'palette' does not exist on type 'Theme'.ts(2339) Check out the code snippet below: const StyledTextField = styled(TextField)(({ theme }) = ...

Redirect the URL in react-snap to a new URL with a forward slash at the end

I recently implemented react-snap to generate static HTML for my website. However, I encountered some SEO issues after implementing react-snap. The old URLs (which were without slashes) are now redirecting to new URLs with slashes. For example: This URL: ...

Encountered an issue while configuring mapping upload for Bugsnag within a React Native project

I'm in the process of incorporating Bugsnag into my React Native project. I want to make sure that any stack traces point to the correct section of the code. However, due to the need for a release app to obtain a stack trace, the source mappings are m ...

Does SMT-LIB make a distinction between an array and a function with no arguments that returns an array?

Do the following two declarations/commands have the same meaning in the SMT-LIB language? (declare-fun a1 () (Array Index Element)) (declare-const a2 (Array Index Element)) When it comes to Z3, an assertion that applies to a1 also applies to a2 without a ...

How can I restrict Threejs Perspective Camera from going below a Y value of zero?

Is there a way to avoid setting a negative position.y for a THREE.PerspectiveCamera? I have implemented a customized TrackballControl that limits camera rotation on the z-axis, but I still want to ensure that my camera remains elevated above the "ground" ...

Customizing font size in React with Material UI: A comprehensive guide on adjusting the font size of the Select component

I'm currently working on a web application that utilizes React along with Material UI. My goal is to adjust the font size of the Select component. I've attempted to achieve this by utilizing the MenuProps property, as shown in the following code ...

What is the best method for showing jQuery/Javascript functions in the HTML <pre> element as a string

I am curious about converting jQuery or JavaScript functions to a string and displaying them in an element like <pre> HTML : <pre></pre> jQuery : function test() { alert('test'); } $('pre').html(test()); // &l ...

Does turning off javascript in a browser impact ajax requests and javascript functions?

My mind is troubled I've been thinking of options like turning off JavaScript in the browser. If I do that, then AJAX and JavaScript functions won't work, right? If so, is there a solution? ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

Pause a YouTube video automatically when the window is not in focus using FancyBox

I have successfully implemented dynamic play/pause functionality for a YouTube video, as demonstrated in my weave. However, I am facing challenges in making it work dynamically with FancyBox using the onBlur event (to pause the video when the window is no ...

Adjusting the settings on my lightbox

Recently, I created a basic lightbox with the following code snippet: Here is the jQuery code: var $overlay =$('<div class="overlay"></div>'); $('body').append($overlay); $('img').click(function(){ $overlay.sho ...

THREE.js - Transformative Vertex Shader for Billboards

I am trying to figure out how to make an instance of THREE.Mesh always face the camera using a vertex shader instead of just relying on the [THREE.Mesh].lookAt() method. After reading through NeHe's Billboarding tutorial, I understand the concept exc ...

Is there a way to create a dropdown menu that transforms into a burger icon on smaller screens, while still housing all of my navigation items within it?

I'm currently working on a segment of my header that includes a navbar with 3 links, as well as a dropdown menu listing additional functionalities. Here is the current code I have: <div class="col-md-4 pt-4"> <nav class="navbar ...