Creating an array based on specific conditions being satisfied (Using Javascript)

I am struggling with a coding problem involving adding users to groups. The goal is to add each user to a group array, with a maximum of 3 users per group. If a group reaches 3 users, it should be moved to another array that collects all the groups. I then need to start a new group for the next 3 users until all users are assigned to groups.


Error -

let group[i] = [];

Unexpected token [


I've been working on this challenge for some time now and can't seem to crack it. It feels like I've hit a wall.

Here's the code snippet where I'm facing issues:

function createGroups(totalPeople){
  let i = 1
  let group[i] = [];
  let array = totalPeople

  totalPeople.map((user) => {

    if(group[i] < 3){
      group[i].push(user)
    }else{
      array.push(group[i]);
      i++
    }
  })
};

The 'totalPeople' array is generated earlier in my script, and this portion seems to be causing trouble. Any suggestions or corrections to help me solve this puzzle would be greatly appreciated! Thank you!

Answer №1

Start by setting up the group as an array:

let count = 1
  let groupArr = [] // Initialized as an empty array
   groupArr[count] = [];
  let allPeople = totalPeople

  totalPeople.map((individual) => {

    if(groupArr[count] =< 3){
      groupArr[count].push(individual)
    }else{
      allPeople.push(groupArr[count]);
      count++
    }
  })

Answer №2

Upon reviewing your code, several issues have been identified:

function createGroups(totalPeople){
  let i = 1
  let group[i] = []; // Issue #1: Declaration issue
  let array = totalPeople

  totalPeople.map((user) => {

    if(group[i] =< 3){ // Issues #2 and #3: Comparison problem 
      group[i].push(user)
    }else{
      array.push(group[i]); // Issue #4: Array push problem
      i++; // Issue #5: Increment problem
    }
  })
};

Issue #1:

The variable group needs to be defined as an array before assigning an index.

let group = []; 
group[i] = [];

Issue #2 :

You should compare the length of group[i] with 3 instead of the value itself.

Issue #3 :

Change the comparison operator from =< to <=. Keep in mind that arrays start at index 0.

Issue #4 :

Check if pushing to array, which refers to

totalPeople</code, produces the desired outcome. Consider using a new array to avoid modifying the original one passed as a parameter, following functional programming best practices.</p>

<p><strong>Issue #5 :</strong></p>

<p>If you increment <code>i
, ensure that group[i] is initialized as an array for subsequent loop iterations.

Different Approach:

After addressing the code issues, here's an alternative method using Array.prototype.reduce:

const totalPeople = ["Joe", "Jack", "Jerry", "Jane", "Mary", "Billy", "Vicky", "Bobby"];

const groupsOfThree = totalPeople.reduce((accumulator, currentPerson, index) => {

  accumulator[accumulator.length-1].push(currentPerson);

  if (index % 3 === 2) {
    accumulator.push([]);
  }

  return accumulator;
}, [[]]);

console.log(groupsOfThree);

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

Is it possible to apply a class without using ng-class?

Seeking a more efficient way to apply conditional classes to multiple elements on a validation form page, I am exploring options to assign one of five potential classes to each form input. While the traditional method involves manually specifying the class ...

Is it a good idea to relocate the document.ready function into its own JavaScript function?

Can the following code be placed inside a separate JavaScript function within a jQuery document.ready, allowing it to be called like any other JavaScript function? <script type="text/javascript"> $(document).ready(function() { $('div#infoi ...

attempting to retrieve a specific nested value using square brackets

I am attempting to track the position of an object associated with a particular row. Ultimately, I require a comprehensive object that includes both the row and the position of a "com" within that row. Below is my code snippet: (g represents a global objec ...

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

Attempt to refresh the JSON data on a website by incorporating an image link from Last FM

I'm relatively new to React Native and have been struggling for quite some time with a persistent issue. I am parsing an online JSON file that contains artist and track information. The only missing piece is the image URL, which I am trying to fetch ...

Retrieve the values by accessing an element upon clicking the "Submit" button

Here is an interesting example that I found on this website I am currently working on a simple webpage to display both the current forecast and extended forecast. This is my Index.html: <!DOCTYPE html> <!-- To change this license header, choose ...

Passing all emitted events from Vue 3 child component to its parent - A complete guide

My Vue components are structured as follows: <TopParent> <!-- Listening for events from EventProducer here --> <Child_1> <Child_2> <Child_3> ... <Child_N> <EventProducer /> &l ...

How can I utilize JQuery to dynamically refresh a dropdown menu?

My dropdown list is initially empty: <div> <label>Boarding Point </label> <select title="Select pickup city" id="boardingDropdown"> </select> </div> I am trying to popula ...

When using Laravel 5.2, JSON data is mistakenly returned as HTML

I've encountered an issue with ajax. My goal is to fetch all the records from a specific table using this ajax call: $('#chooseInvBtn').on('click', function(){ $.ajax({ type: "POST", url ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

I encountered an issue while constructing a React application. An error message popped up indicating: "Warning: Can't execute a React state update on a component that is not mounted"

Having difficulty pinpointing the source of the error message displayed below. Should I focus my investigation on the specific lines mentioned in the console, such as Toolbar.js:15? Is the console indicating that the error lies there? Additionally, what i ...

Button cannot be activated upon selecting a row

The goal is to activate a button when a row is selected. However, the button remains disabled even after selecting a row. Below is a snippet of the code as well as a screenshot showing the issue [error_1]: onInit: function () { var oViewMode ...

How can I successfully transmit the entire event during the (change) event binding with ng-select in Angular 14?

I'm working on Front end Code <ng-select formControlName="constituencyId" placeholder="Select Constituency" (change)='onContituencyChanged($event)'> > &l ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Steps for replacing the firestore document ID with user UID in a document:

I've been attempting to retrieve the user UID instead of using the automatically generated document ID in Firebase/Firestore, but I'm encountering this error: TypeError: firebase.auth(...).currentUser is null This is the content of my index.js ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

What is the method for conducting an Ajax request?

Currently, I am deeply involved in a personal project to enhance my skills with Rails. The project involves developing a task management application that encompasses three primary states: todo, in progress, and done. After numerous days of trial and error, ...

Error in Node.js: The res.send method is undefined

I'm having some issues with my first attempt at creating a simple Counter Strike API bot using nodeJS. The problem lies with the res.send function, as I keep getting an error message saying "res.send is not a function" every time I try to use it. Movi ...

Specific category of location on Google Maps

I am currently building an application using Cordova and Ionic. I need to implement a map in my app that will display only specific establishments, such as police stations or doctors' offices. This is the code I have so far: var posOptions = {time ...