Unpack an array with entries and an iterator

I am working with an array of objects, each containing the same properties. My goal is to create a function that will return an array of arrays, where each inner array holds values based on the property names of the objects.

Here is an example input:

input: [
    {
       test1: '10',
       test2: '15',
       test3: '14',
       test4: '22'
    },
    {
       test1: '4',
       test2: '1',
       test3: '45',
       test4: '2'
    },
    {
       test1: '5',
       test2: '16',
       test3: '7',
       test4: '0'
    }
]

The expected output should be an array of arrays where each sub-array contains only elements whose keys are the same. For instance, the values of test1 in an array would be: [10, 4, 5]:

output: [[10, 4, 5], [15, 1, 16], [14, 45, 7], [22, 2, 0]]

My current approach involves using array.entries() and iterator but the result is not correct as the values are stored in the incorrect order. Here is the snippet of code:

let output = [];
sort(input) {
    const results = [[], [], [], []];
    if (input.length > 0) {
      const iterator = input.entries();
      let item = iterator.next();
      while (!item.done) {
        const data = Object.values(item.value[1]);
        results.forEach((result, index) => {
          if (item.value[0] == index)
            result.push(parseFloat(data[index]));
        });
        item = iterator.next();
      }
    }
    output = results;
  }

Can you suggest a way to make this function work correctly?

Answer №1

One clever method involves utilizing the key-order of the first object to establish the final output order:

const rearrangeData = (input = []) => 
  Object .keys (input [0] || {}) 
    .map (k => input .map (x => x [k]))

const dataInput = [{test1: '10', test2: '15', test3: '14', test4: '22'}, {test1: '4', test2: '1', test3: '45', test4: '2'}, {test1: '5', test2: '16', test3: '7', test4: '0'}]

console .log (rearrangeData (dataInput))
.as-console-wrapper {min-height: 100% !important; top: 0}

This technique pulls out the common keys from the initial object and uses them as a reference for extracting information from each subsequent object.

Answer №2

const data = [{
    item1: '20',
    item2: '30',
    item3: '24',
    item4: '42'
  },
  {
    item1: '6',
    item2: '8',
    item3: '35',
    item4: '9'
  },
  {
    item1: '15',
    item2: '26',
    item3: '17',
    item4: '3'
  }
]

// create an empty array to store the result
let output = [...Array(Object.keys(data[0] || {}).length)].map(x => []);
// fill in the values
data.forEach(value => {
  // assign each value to its corresponding position in the result array.
  Object.values(value).forEach((value, index) => {
    output[index].push(value)
  });
});
console.log(output);

Answer №3

That's an intriguing perspective. Personally, I prefer a more minimalist approach with fewer elements. I find it puzzling why the function is labeled "sort" when there isn't any sorting involved.

"use strict";

function organizeData(data)
{
  var stacks, stacknames;

  stacks = [];
  stacknames = {};

  data.forEach(item => {
    var k;

    for (k in item)
    {
      if (!(k in stacknames))
      {
        stacknames[k] = stacks.length; // map name to index
        stacks.push([]); // allocate new stack
      }

      stacks[stacknames[k]].push(parseFloat(item[k]));
    }
  });

  return stacks;
}

var input = [
    {
       test1: '10',
       test2: '15',
       test3: '14',
       test4: '22'
    },
    {
       test1: '4',
       test2: '1',
       test3: '45',
       test4: '2'
    },
    {
       test1: '5',
       test2: '16',
       test3: '7',
       test4: '0'
    }
];

var output = organizeData(input);

console.log(output);

Answer №4

Using the reduce method can simplify this process.

var inputData=[ { test1: '10', test2: '15', test3: '14', test4: '22' }, { test1: '4', test2: '1', test3: '45', test4: '2' }, { test1: '5', test2: '16', test3: '7', test4: '0' }];

var finalOutput = Object.values(inputData.reduce((accumulator, element)=>{
  Object.entries(element).forEach(([key,value])=>{
    accumulator[key] = accumulator[key] || [];
    accumulator[key].push(value);
  })
  return accumulator;
},{}));

console.log(finalOutput)

Answer №5

Utilizing a double-loop structure can provide the intended outcome in the following manner.

let input = [
    {
       value1: '10',
       value2: '15',
       value3: '14',
       value4: '22'
    },
    {
       value1: '4',
       value2: '1',
       value3: '45',
       value4: '2'
    },
    {
       value1: '5',
       value2: '16',
       value3: '7',
       value4: '0'
    }
];

const fetchValues = (datum) => {
  // Identifying keys within the object
  let keys = Object.keys(datum[0]);
  // Initializing the result with vacant arrays
  let temporary = [...Array(Object.keys(datum[0] || {}).length)].map(x => []);

  for (let i=0; i<data.length; i++) {
    for (let j=0; j<keys.length; j++) {
      let phrase = keys[j];
      temporary[j].push(data[i][phrase]);
    }
 }
 console.log(temporary);
}

fetchValues(input);

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

What is the best way to read a local text file and store its contents in a string variable within a

Within my ReactNative project, I am seeking to retrieve the content of static text files and store it in a string variable. Here is an example of how I would like to achieve this: var content = loadPlainTextFile("resources/tags.txt"); var tags = content.s ...

How to retrieve the time duration in minutes between a start and end time in JavaScript to

I have conducted a thorough search on Stack Overflow and other platforms but could not find an answer to my specific question. While I did come across posts related to this topic, they did not address the issue I am facing. Problem: My challenge involves ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...

Is it possible to attach React Components to Elements without using JSX?

In my React Component, I have the following code: import React, { useEffect } from 'react' import styles from './_PhotoCollage.module.scss' import PhotoCard from '../PhotoCard' const PhotoCollage = ({ author }) => { let ...

What is the best way to combine a list of jsonNodes into a single jsonNode?

I've been working with the Jackson library in Java and I have a collection of objects that serve as wrappers for jsonNodes. I need to convert this list of jsonNodes into a single jsonNode. I attempted the following method: public JsonNode converte ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

Implementing pagination within nested ng-repeat in Angular app

I am currently utilizing Angular along with the Material library in my project. I am facing an issue with two nested ng-repeat loops within md-tables. The problem lies in the fact that the variable is getting overridden with each request in the nested loop ...

Meteor Infinity: the astronomy .save functionality seems to be malfunctioning

Encountering an issue where I am receiving a "post.save is not a function" error when trying to use the .save() function with astronomy v2. The error occurs when attempting to call the .save() function to insert a new document into the database using a Met ...

Designing a menu header against a specific background color resulting in misalignment

I have been working on creating a menu header for my website. If you would like to take a look, here is the link to my jsfiddle page. Unfortunately, I am facing an issue where all my images and text should remain in that grey color scheme but somehow it& ...

What is causing the digest loop from this angular filter grouping?

My goal is to showcase a variety of items in batches of N at a time. The reason for chunking the items is because I need them to be laid out in a tabular or gridded format (each group of N items forms a row, with each item being a column). Below is my atte ...

React Application Issue 'Error: React is not defined'

I've been working on developing an app using react, but for some reason, it's not functioning properly and I'm struggling to pinpoint the issue. The code compiles without errors using babelify, however, it throws an exception during executio ...

Exporting a module with Node.js is a crucial aspect of building

Within my custom module, I have successfully set up an export function. module.exports = function(callback) { var request = require("request") var url = "http://sheetsu.com/apis/94dc0db4" request({ url: url, json: true }, ...

Is it considered acceptable to utilize a v-model's value as the basis for an if-statement?

How can I incorporate the v-model="item.checked" as a condition within the validations() function below? <table> <tr v-for="(item, i) of $v.timesheet.items.$each.$iter" > <div> <td> ...

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

In what format is the parameter accepted by the .getDay() method?

Here's the plan: I need to extract information from an input element with type set as date. This data will then be stored in a .json file and later parsed when the program is initiated. Subsequently, I aim to utilize the date.getDay() function to dete ...

The date entered in the input field should also appear in all other textboxes on the

I currently have 2 tables set up on my page. In the first table, there is a textbox (txt1) that includes a date picker. The second table contains 5 similar textboxes (txt2, txt3, txt4, txt5, txt6) also with date pickers. My requirement is as follows: Ini ...

Is bower install failing to detect a local npm package?

After running bower install, I encountered the following error message: $ bower install module.js:340 throw err; ^ Error: Cannot find module 'minimist' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._l ...

My page is experiencing delays due to setInterval

Currently, I am delving into the world of Chrome Extension development and am faced with a roadblock in replacing elements on a live chat page. While most of my tasks are running smoothly, the one thing causing issues is the setInterval option that trigger ...

Navigating to a different component with react-bootstrap-table-next?

I have a collection of coding challenges in a table format. I want the user to be able to click on a challenge name and be routed to a separate page showcasing the details of that specific problem using a Problem component with unique props. Currently, I ...

Trouble with document updates in MongoDB/Mongoose causing a delay?

I am currently working on updating an object nested in an array in my application. When I test this functionality using Postman, I am experiencing a delay that requires me to make two requests in order to see the updated value. if (taskStatus) { cons ...