Using JavaScript to divide an associative array into separate arrays

I am dealing with an array of clubs

var clubs =[{
    team: {name: "fcb barca", rank: 4},
    team: {name: "man utd", rank: 16},
    team: {name: "man city", rank: 36},
    team: {name: "fcb liverpool", rank: 57}
}];

The task at hand is to separate this array into two arrays, resulting in

  teams["fcb barca", "man utd" , "man city", "fcb liverpool"];
  rank[4,16,36,57];

I have attempted the following code but it does not seem to be functioning properly

var team = [];
 var rank = [];
 for(var i = 0; i < clubs.length; i++){
   var tempArray1 = teams{{name: clubs[i].name, grade: clubs[i].rank}};
   var tempArray2 = teams{name: clubs[i].name, grade: clubs[i].rank};
   team.push( tempArray1 );
   rank.push( tempArray2 );
 };

console.log(team);
console.log(rank);

Answer №1

In a few moments, I'll probably regret pointing this out to you. But for now, your code is far from valid.

Let's go through what's incorrect here:

clubs[{
    team{name: "fcb barca", rank: 4}
    team{name: "man utd", rank: 16}
    team{name: "man city", rank: 36}
    team{name: "fcb liverpool", rank: 57}
}];

Firstly, clubs needs a variable declaration like:

var clubs = [

Also, you're defining clubs as an array with [, but the array only contains one object because of the { immediately following it.

Another issue is:

team{ 

is not a correct JavaScript object syntax. It should be team : {. Additionally, you need commas to separate the objects:

team : {name: "fcb barca", rank: 4},
team : {name: "man utd", rank: 16}

Corrected, it would look like:

var clubs = [{
    team : {name: "fcb barca", rank: 4},
    team : {name: "man utd", rank: 16}
}];

Furthermore, having several keys with the same name team in one object won't work.

The corrected code should resemble this:

let clubs = [
    {name: "fcb barca", rank: 4},
    {name: "man utd", rank: 16},
    {name: "man city", rank: 36},
    {name: "fcb liverpool", rank: 57}
];

Alternatively, if you want objects representing teams:

let clubs = [
    { team: {name: "fcb barca", rank: 4} },
    { team: {name: "man utd", rank: 16} },
    { team: {name: "man city", rank: 36} },
    { team: {name: "fcb liverpool", rank: 57} }
];

Once your syntax is fixed, you can loop through it like this:

let teams = [];
let ranks = [];

clubs.forEach(function(club){
    teams.push(club.name);
    ranks.push(club.rank);
});
console.log(teams);
console.log(ranks);

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

When working with express.js, how can you determine whether to utilize a middleware or a standard function in your code?

While working on my project, I decided to create a login authentication module using a standard function. However, after seeing other developers utilize middleware for the same purpose online, I became unsure about when it is more appropriate to use middle ...

Employing jQuery to add div elements, with each div possessing a distinct identifier

Hey, I'm working on using jQuery to dynamically generate cards with unique IDs and random numbers. I believe there must be a better way to achieve this. Could you help me with two things? First, how can I continuously add random numbers to the cards? ...

Creating a standard login.js file for seamless integration with nightwatch.js testing

When creating tests for my web application, I need to first simulate a login before proceeding with the rest of the tests to access inner pages. Currently, I am in the process of refactoring the code so that I can create an 'include' for common f ...

Submit form in a new tab and refresh the current page

It seems like my mind is hitting a roadblock, I'm having trouble finding a better solution for this particular issue: I need to send a form via POST method (with data handling on the server) and have it open in a new tab with a custom URL containing ...

Output the result of a PHP script inside a JavaScript code

I'm having trouble getting the code below to display the success word. Can anyone spot what's wrong with it? Appreciate any help in advance. <script type="text/javascript"> function verification(){ var s = document.test_form.textfiel ...

Next.js App encounters a missing API route (The requested page is not found)

I have been working on a Next.js app and I created an api route for sending emails. Everything is functioning properly in my development environment. However, after deploying to production, I encountered a 404 error with the message "The page could not b ...

In what specific way can I collect the contents from the open file along with the names present in the files and store them into my string vector?

#include <iostream> #include <string> #include <fstream> #include <vector> #include <iomanip> using namespace std; int main() { char answer = 'y'; while (answer == 'y') do { ...

Unable to halt operation when xmlhttprequest.responseText is equal to a particular value

Currently, I am incorporating XmlHttp with Java servlets in the following manner: function btnSave_onclick(){ var xmlHttp; var responseText; if (condition){ var para= "someParamsHere"; var url = "urlHere"; if (window.XMLHttpRequest) { ...

Height and Width Dilemma in Visuals

Can you help with changing image resolution using jQuery? I have a background image applied to the body using CSS/PHP. My goal is to make the image fill the entire window by applying the screen height and width, without using repeat style. The code I am c ...

Difficulties encountered when trying to interact with buttons using JS and Bootstrap

I'm working with a Bootstrap 5 button in my project and I want to access it using JavaScript to disable it through the attribute. Here is the code I've been testing: Script in Header: ` <script> console.log(document.getElementsByName(& ...

A function that iterates through an array and applies a formula to each element based on a conditional statement

I am working with an array of floats, denoted as "array=([2.0, 7.0, 8.0, 1.0])". My objective is to create a second array that will apply one of two formulas to the elements of the first array based on a conditional "if" statement applied to corresponding ...

jQuery: Modifying the Style of obj "th" Element

I am looking to update the style of my selection using jQuery. After using this module to retrieve all items, I have a list of cells with new coordinates. //cell list with new coordinates cl = Object {0-0: th, 0-1: th, 0-2: th, 0-3: th, 1-0: td…}, id = ...

Searching for a solution on how to retrieve data server-side in the newest version of Next.js? Attempted to use getStaticProps but encountering issues with it not executing

Currently tackling a project involving Django Rest Framework with Next.js, and encountering a roadblock while trying to fetch data from the API. Data is present at the following URL: http://127.0.0.1:8000/api/campaigns, visible when accessed directly. The ...

Difficulty with obtaining .responsetext in AJAX and PHP

On my real estate website, I have a form for users to 'Add a Property'. Although I will implement form validation later on, here is the current html/js code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Having trouble passing a JavaScript variable through AJAX requests

In this particular script, I am encountering an issue where the variable "encrypted" is expected to be sent via ajax to upload.php, however I am unable to achieve this. Oddly enough, if I substitute the "encrypted" variable with another variable in the a ...

How to send a global variable to an event callback function in JavaScript?

I have encountered an issue in the following code where I am attempting to pass mydata to the callback function. This is just a small part of a larger problem that I am facing and I suspect it may be related to scope. Can anyone help me identify what is wr ...

What is the most effective method for dynamically showcasing buttons in AngularJS?

Hello all, I'm currently learning AngularJS and I was wondering if anyone could recommend the simplest and most effective method for dynamically displaying links from AngularJS to HTML. I am looking to display a variable number of buttons in my HTML ...

Remove bulleted list from HTML using JavaScript DOM

My task involved deleting the entire "agent" array using the removeChild() function, requiring the id of a <ul> element. However, I faced an issue as I couldn't set the id for the "ul" due to using the createElement() function. //old code < ...

Issue with React Material-UI drawer not functioning properly when invoking a child component function from the parent

Here is a piece of code I have for the App.js file: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Child from './child'; class App extends Component { render() ...

Can a function be provided as an argument to another function within a React component?

I have created a const function in React as shown below: const LazyOptions = () => { return <Cascader options={options} loadData={loadData} onChange={onChange} changeOnSelect />; }; Next, I defined the onChange function outside and passed it in ...