Arrange certain items from one array into a different array

As part of a project, I am required to organize this array that includes both strings and numbers. The strings act as indicators for which array the number should be stored in.

let myArray = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk']
let talk = []
let perfo = []
let init = []

for (let i = 0; i < myArray.length; i + 2) {
    if (myArray[i + 1] == 'talk') {
        talk.push(myArray[i])
    } else if (myArray[i + 1] == 'perfo') {
        perfo.push(myArray[i])
    } else if (myArray[i + 1] == 'init') {
        init.push(myArray[i])
    } else {}
}

The expected output should be:

talk [22, 42], perfo [35], init [42]

However, it appears that the for loop is not being executed properly.

Answer №1

An object differs from an array in that it uses strings instead of numbers as indexes, allowing us to reconstruct the initial array using an object.

let myArray = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk']

let arrays = {}
for (let i = 0; i < myArray.length; i+=2) {
  const arrayName = myArray[i+1];
  
  if (arrays[arrayName]) {
    arrays[arrayName].push(myArray[i])
  } else {
    arrays[arrayName] = [myArray[i]]
  }
}

console.log(arrays);
// [object Object] {
//  init: [35],
//  perfo: [31],
//  talk: [22, 42]
// }

Answer №2

If you have an object containing arrays and want to push values into it, you can follow this approach.

let data = [22, 'talk', 31, 'perfo', 35, 'init', 42, 'talk'],
    talk = [],
    perfo = [],
    init = [],
    temp = { talk, perfo, init },
    i = 0;

while (i < data.length) {
    let [value, key] = data.slice(i, i += 2);
    temp[key].push(value);
}

console.log(talk);
console.log(perfo);
console.log(init);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Having trouble loading my app.js in Angular - Seeking help on Coursera!

I've followed the instructions provided thus far and inserted the HTML code accordingly. However, upon attempting to load the page, all I see is: The tabs: The Menu Appetizers Mains Desserts The description: image: dish.name , dish.name , dish.labe ...

Node.js Express refuses to serve .js files with absolute URLs

I have encountered a perplexing issue with two files located in /public/widget, namely help.html and help.js http://localhost:8084/widget/help.html When entered into the address bar, it functions normally However, when attempting to access http://local ...

The function in JavaScript that is supposed to receive a value from a servlet is malfunctioning

I am encountering an issue with my JavaScript method that is supposed to display an alert on the document body's onload event. The method takes a single string parameter provided by the servlet. Although the value is retrieved successfully, it seems ...

Organize information into an array format to create a tournament bracket using PHP and JSON

In my dataset, I have brackets that accept data in the following format: [// Round 1 bracket [// row 1 { "name" : 'test name', 'id' : 1 }, { "name" : 'te ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

Having difficulty submitting an AJAX registration form

My goal is to implement a code that allows users to register and then load a new page using AJAX. Step 1: Users enter their details in the registration form within register.php. When they submit the form using the "reg-submit" input, the details are sent ...

The implementation process of asp.net server controls explained

I'm curious about how server controls like calendar and treeview are implemented in ASP.net. I thought they were built using JavaScript, but what happens if JavaScript is disabled on the web browser? Can someone shed some light on this? Thanks. ...

Is there a way to render the hidden faces of the cube to the framebuffer? (The sides that are not visible from my current perspective)

I am currently working on implementing volume rendering in WebGL using the Three.js library. While I have experience with pure WebGL, I'm facing challenges finding a similar approach in Three.js. Here are the issues at hand: 1) How can I render the ...

How can I retrieve a specific set of Firebase documents based on a property's value in a collection?

I'm currently developing a social media app using Firebase and React, and I need to implement a search bar that suggests users based on the input value. For example, when typing "F," I want to see suggestions like Foo and Bar, similar to common social ...

The useState setFunction does not alter on OnClick events

My useState element is causing issues because the function doesn't get called when I click on it. I've tried multiple solutions and debugging methods, but it seems like the Click event isn't being triggered no matter what I do. const [moda ...

Utilizing Django to organize and categorize a list of dictionaries

After combining data from two models in Django, I have generated a list of dictionaries where each dictionary represents a row in a table that is displayed on the client side. Now, I am looking for a way to sort this list based on each of the different co ...

how to eliminate duplicate elements from a multi-dimensional array using Python

I am working with a 2-d array xx=[[a,1],[b,2],[c,3]] Currently, I am attempting to eliminate duplicate entries from it. While a simple code like xx=list(set(xx)) works for a simple 1-D array, it results in an error when applied to 2-d elements temp = ...

Modify the MUI time picker to display as a digital clock inside a DateTimePicker widget

I need to update my MUI DateTimePicker component to use the DigitalClock time picker instead of the Analog Clock picker. The current component has two steps, first picking the date from a calendar and then selecting the time. This change is only necessary ...

Display a block by using the focus() method

My objective is : To display a popin when the user clicks on a button To hide the popin when the user clicks elsewhere I previously implemented this solution successfully: Use jQuery to hide a DIV when the user clicks outside of it However, I wanted to ...

Access the environment variables generated throughout a collection run in the Newman Library

Is there a way to access environment variables created in collection requests while using Newman as a library and executing through Node.js? Currently, I have the following: Example Although this setup works partially, I encounter an issue due to my eve ...

Transmitting HTML content via JSON with AJAX

Currently, I am integrating with the Mercado Livre API. Due to the fact that users can input HTML in the description field, it is necessary for me to accommodate this feature. My approach involves utilizing AJAX to interact with Mercado Livre. However, I ...

Converting a character array to a Java string can be done using printf for integer types, however, it does

Our vendor provides us with an API that includes a struct defined as: typedef struct { char duo_word[8]; } duo_word; This data structure is sent to us by the vendor, and we then need to pass it to our Java application using JNI. printf("Number: ...

Sorting through JSON data obtained through YQL

Hello coding enthusiasts, After facing challenges with CORS in an AJAX project, I discovered a workaround using YQL to successfully retrieve JSON data. Now, I'm looking for ways to access and organize this data according to my preferences. Below is t ...

The console does not display the JSON data for requests and responses

I have successfully set up a server inside of VSCode, but unfortunately the request and response logs that I usually see in my terminal when running the server with npm start are not appearing. I would really like for them to display in the Debug Terminal ...

What methods can I use to transfer data from one domain to another domain utilizing Ajax JSONP?

Example: The URL of my site is "http://localhost:54887/CustomOrdering.html", but I want to retrieve data from another site "http://localhost:27746/Orders.aspx". In order to do this, I have implemented the following code in my CustomOrdering.html: function ...