Arranging objects in an array format

Within my array of objects (referred to as "data"), the first two indexes are outlined below:

0: Object

granularity_time: "total"

granularity_geo: "nation"

location_code: "norge"

border: "2020"

age: "90+"

sex: "female"

year: "1900"

week: "1"

yrwk: "1900-01"

season: "1899/1900"

x: "24"

date: "1900-01-01"

n: "219"

date_of_publishing: "2022-01-12"

    tag_outcome: "death"

1: Object

granularity_time: "total"

granularity_geo: "nation"

location_code: "norge"

border: "2020"

age: "90+"

sex: "male"

year: "1900"

week: "1"

yrwk: "1900-01"

season: "1899/1900"

x: "24"

date: "1900-01-01"

n: "127"

date_of_publishing: "2022-01-12"

tag_outcome: "death"

The data differentiates between men and women within the same age group, organized in pairs of objects. For instance, index 0 represents women aged 90+, while index 1 signifies men aged 90+. This pattern continues with index 2 for women aged 80+, index 3 for men aged 80+, and so on.

To reorganize this data structure such that each index contains a pair of objects representing men and women in the same age group, one could format it similarly to the following code snippet:

const newData = [
{
  woman: data[0],
  men: data[1]
},
{
  woman: data[2],
  men: data[3]
},
{
  woman: data[4],
  men: data[5]
},
{
  woman: data[6],
  men: data[7]
},
{
  woman: data[8],
  men: data[9]
},
{
  woman: data[10],
  men: data[11]
},
{
  woman: data[12],
  men: data[13]
}

];

An attempted function was made to iterate over the data and implement this desired formatting. However, the entries turned out undefined rather than paired correctly. Below is the function in question:

const formatData = (data) => {
    const newData = [];

    data?.map((item, i) => {
      i % 2 === 0 ? newData.push({ woman: item[i], men: item[i++] }) : null;
    });

    return newData;
  };

I am seeking guidance on what might be missing or incorrect within the function. Any insights would be greatly appreciated.

Answer №1

Given that the result is only half of what was provided, one might argue it's more akin to a transform() method...

const collection = [{ gender: "m", name: "bob" }, { gender: "f", name: "linda" }, { gender: "m", name: "ted" }, { gender: "f", name: "alice" }];

const transformedData = collection.reduce((accumulator, object, index) => {
  index % 2 ? accumulator[accumulator.length-1].girl = object : accumulator.push({ boy: object })
  return accumulator;
}, []);

console.log(transformedData)

Answer №2

To achieve the desired output from your original data array, you can utilize both Array.from() and Array.map().

The resulting array will have a length equal to half of the initial data array's length. Each alternate item will be designated to either the women or men property within each element of the final array.

const template = { year: 1900, location_code: 'norge' };
// Assume there is an input data array...
const data = Array.from({length: 14}, (v,k) => ({...template, id: k, gender: ( k % 2 === 0 ? 'female':'male' )}));

const result = Array.from( { length: data.length / 2 }, (v, idx) => { 
    return { women: data[2*idx], men: data[2*idx + 1],  };
})

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

Answer №3

This method seems to be functioning properly, however, I am hesitant about its adherence to best practices as it solely relies on the map function to extract a particular value.

const reformatData = (data) => {
  const modifiedData = [];
  data?.map((item, index) => {
    if (index % 2 === 0)
      modifiedData.push({ woman: data[index], men: data[index + 1] });
  });
  return modifiedData;

};

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

iterating over a array of characters in c++

#include <iostream> #include <string> using namespace std; bool isValidID(char [], int); int main() { const int length = 8; char ID[length]; cout << "Please enter an ID in the format "; cout << "ABC1234\n"; ...

I'm looking to develop a custom CKEditor plug-in that will allow users to easily drag and drop elements within the editor interface

Upon observing that dragging and dropping text or images within a CKEditor editor instance does not trigger the "change" event, I devised a temporary solution by implementing code triggered by the "dragend" event. However, my ultimate goal is to create a C ...

VueJS together with Firebase: The guide to password validation

I am currently working on a web form developed using VueJS that enables authenticated users to modify their passwords. The backend system relies on Firebase, and I am facing a challenge in validating the user's current password before initiating the p ...

Enhancing Your Model with Additional Details using Angular Formly

I have been utilizing Angular Formly to display forms generated from the JSON response received from services. However, I have a few inquiries. Is it feasible to retrieve data in a field (templateOptions.label, for instance) to include in the model? ...

What are some effective strategies for developing an API that has a prolonged response time?

While working on an API endpoint that requires calling multiple external services/DBs, I want to ensure that my users do not face delays in the process. However, the outcome of this process is crucial for their experience. My initial idea is to enqueue th ...

What are some techniques for concealing a rendered element retrieved using the fetch API?

Currently, I am grappling with a coding challenge that requires me to extract data from https://jsonplaceholder.typicode.com/users using the fetch API function along with bootstrap and jquery. To display the data in a div element, I utilized the array.map( ...

"Implementing a drop-down feature for various div elements based on their unique ids

What is the best way to implement dropdown menus in multiple divs with different IDs? I have a user stream where adding a dropdown menu for actions like delete and edit on each post only opens the dropdown in the first post. I know this needs to be handle ...

Create a double array in C and populate it with integer values

Currently learning some C programming and have an exercise for university where I need to create a double array filled with integer values. Here is my code: #include <stdio.h> #include <stdlib.h> int main( int argc, char *argv[] ) { int size ...

False return - Inoperative link - Scroll option

I have a JavaScript drop-down menu that is functioning correctly, but when I click on one of the links in the dropdown, the link does not work. I suspect it has something to do with my "return false/true" setup. Here's my JavaScript code: function d ...

Utilize Angular HttpClient to send a new Array created from fresh FormData to the server

I have an Array of Objects that contains files (images) with unique fields. When submitting, a new Array of Objects is sent to the server using Angular HttpClient. // Original Array of Objects let originalArray = [ { "name": & ...

JavaScript believes that the function is not defined, despite its clear existence

This question pertains to an issue regarding the recognition of Bookshelf.js model function as a function. The error message "Function is undefined, Bookshelf.js model function is not being recognized as a function" arises when trying to POST to the login ...

Tips on how to showcase JSON data retrieved from a RESTful API using JavaScript or jQuery

Is there a way to avoid repeating myself when displaying all content from my data array, like in the example below? // Program guide Rest $(document).ready(function() { $.ajax({ cache: false, url: "http://engrid2media.com/nextt/api/epg/s ...

What is the most efficient way to load data just once when a user reaches the bottom of the page?

I am encountering an issue with a webpage that dynamically loads HTML from a PHP script which scraps image links from another site when the user scrolls to the bottom of the page. The problem is that the scraping script takes some time to complete, causing ...

Hide the menu when a user clicks on any of its options

On a next.js website, there is a hidden panel that slides out from the edge when a button is clicked. Inside the panel, there is a menu. The panel and the menu are separate components. The goal is to have the panel open and close when the button is clicked ...

Can you explain the contrast between a React event and a DOM event?

I've spent some time looking for a solution to this, but unfortunately I haven't been able to find anything online. This question seems quite intriguing. Could someone possibly provide an explanation if there is indeed a significant difference? ...

Iterating through a JavaScript object to calculate the total sum of all its values

I'm currently working on a task that involves iterating through an object to determine the total number of appearances for each candidate and displaying that information on the webpage. This particular challenge has been quite puzzling for me. As som ...

Retrieve an integer array containing values that exceed a specified threshold

I am struggling to add values to an int[] array that meet a specific threshold. Unfortunately, my current code is not returning the expected output. For instance, instead of getting "Output for values above 78: [85, 93, 81, 79, 81, 93]", I am receiving [ ...

JavaScript never forgets to validate the user input

Forgive me for my lack of experience, but I am new to this and seeking guidance. I am struggling to find a straightforward example on how to validate HTML input using JavaScript. Currently, I am working on a search function and need help in implementing ...

Leverage the power of an HTML button to trigger a JavaScript function

To find the solution when inputting values for a, b, and c (for example, a=1, b=-3, c=-4), simply press the button. function solve(a, b, c) { let x1 = (-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a); let x2 = (-1 * b - Math.sqrt(Mat ...

Retrieve mismatching data from two arrays of objects based on a shared column, where one of the columns contains records separated by pipes

Currently facing a challenge in a logic for retrieving records by checking the master data. The goal is to find records where a name from a pipe separated column in one array is present, but not found in another master data containing array. Here's an ...