Generate arrays by extracting each individual value from a multidimensional array based on their corresponding index objects

Witness the example of my primary array:

[
  {
    'data': [{'value': 'Yellow'}, {'value': 'Tiny'}, {'value': 'Excellent'}]
  },
  {
    'data': [{'value': 'Green'}, {'value': 'Large'}, {'value': 'Poor'}]
  },
  {
    'data': [{'value': 'Blue'}, {'value': 'Medium'}, {'value': 'Superb'}]
  }
]

The desired outcome is:

[
  ['Yellow', 'Green', 'Blue'],    
  ['Tiny', 'Large', 'Medium'],
  ['Excellent', 'Poor', 'Superb']       
]

I have attempted using forEach, for...in, filter, and so on. However, I have not been able to achieve the expected result.

Answer №1

To organize the data, you can implement a combination of reduce() and forEach(). Within the loop of reduce(), utilize forEach() to iterate over each element in the array. Use the index within the forEach loop to identify the specific array where the value should be stored. If there is no existing value at that index, create a new array and push the value into it:

let information = [{'information': [{'detail': 'Red'},{'detail': 'Small'},{'detail': 'Good'}]},{'information': [{'detail': 'Black'},{'detail': 'Medium'},{'detail': 'Bad'}]},{'information': [{'detail': 'White'},{'detail': 'Large'},{'detail': 'Best'}]}]

let arrangedData = information.reduce((arr, item) => {         // review each item in the information array
  item.information.forEach(({detail}, index) => {              // explore each item in the item.information array
    (arr[index] || (arr[index] = [])).push(detail)             // generate an array if needed and append detail to it
  })
  return arr
},[])

console.log(arrangedData)

Answer №2

If you're looking to filter output based on specific conditions, consider using the filter() method as demonstrated below.

filter() method is essentially utilized when one wishes to obtain a filtered output based on certain criteria.

var a = [
    {
       'data': [
       {
          'value': 'Red'
       },
       {
        'value': 'Small'
       },
      {
        'value': 'Good'
       }
     ]
    },
    {
        'data': [
        {
        'value': 'Black'
        },
        {
        'value': 'Medium'
        },
       {
        'value': 'Bad'
       }
     ]
   },
     {
     'data': [
      {
        'value': 'White'
      },
      {
        'value': 'Large'
      },
      {
        'value': 'Best'
      }
      ]
     }
    ]


var obj = {};

for(var o of a) {
    for(var i in o.data) {
        if(obj[i] === undefined) {
            obj[i] = [o.data[i].value];
        } else {
            obj[i].push(o.data[i].value);
        }
    }
}

console. log(obj);
/*
{ '0': [ 'Red', 'Black', 'White' ],
  '1': [ 'Small', 'Medium', 'Large' ],
  '2': [ 'Good', 'Bad', 'Best' ] }
*/

Answer №3

Here is how I tackled your issue: I utilized a main loop that iterates over the specified number of properties you wish to access, utilizing the functionality provided by the method Array.from()

let a = [
    {'data': [{'value': 'Red'}, {'value': 'Small'}, {'value': 'Good'}]},
    {'data': [{'value': 'Black'}, {'value': 'Medium'}, {'value': 'Bad'}]},
    {'data': [{'value': 'White'}, {'value': 'Large'}, {'value': 'Best'}]}
];

// The new array.
let newArr = [];

// Number of properties for each "data" object.
let keys = 3;

for (let k = 0; k < keys; k++)
{
    newArr.push(Array.from(a, v =>  v.data[k].value));
}

console.log(newArr);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Alternatively, instead of using Array.from(), you can opt for map(), like so:

for (let k = 0; k < keys; k++)
{
    newArr.push(a.map(v => v.data[k].value));
}

Example:

let a = [
    {'data': [{'value': 'Red'}, {'value': 'Small'}, {'value': 'Good'}]},
    {'data': [{'value': 'Black'}, {'value': 'Medium'}, {'value': 'Bad'}]},
    {'data': [{'value': 'White'}, {'value': 'Large'}, {'value': 'Best'}]}
];

// The new array.
let newArr = [];

// Number of properties for each "data" object.
let keys = 3;

for (let k = 0; k < keys; k++)
{
    newArr.push(a.map(v =>  v.data[k].value));
}

console.log(newArr);
.as-console {background-color:black !important; color:lime;}
.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

Transfer the chosen language from the uib-dropdown language selector to the $scope variable

Here is a HTML template that allows the user to select a language: <div class="btn-group" uib-dropdown> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" uib-dropdown-toggle> ...

What is the best way to extract information from a text file and store it in an array of structures?

Looking to retrieve information from a file named fields.txt that contains data about the members of the struct Fields. {1, 0, 7.4, 39.5, 5.33784}, {3, 1, 4.6, 27.9, 6.06522}, {5, 2, 2.2, 12.5, 5.68182}, {8, 0, 14.5, 86, 5.93103}, {11, 1, 8, 43.8, 5.4 ...

The Power of AngularJS Directives in Harnessing jQuery DOM Event Bindings

I have developed a new directive and have some doubts about the binding syntax like element.bind("click", function(){}). Every time the link function of the directive is called, it creates a duplicate binding. What is the best Angular approach to handle th ...

Exploring the World of C Pointers and Arrays

Can someone please explain the meaning of this code snippet in C? MDMA_Sobel_In_Des.StartAddress = (void *) (&Sobel_In_Buf0[0]); I am particularly curious about the right-hand side statement. Why is the address of the variable not directly assig ...

Displaying a loading indicator while a file is downloading and the page is being

Is there a way to show a loading indicator while a PDF is being generated in PHP? I redirect to a separate page for the PDF generation process, but the original page stays open and simply downloads the file once it's ready. How can I make a loading in ...

Getting the (x,y) Coordinate Value from jQuery Script and Saving it as a NSString

div tag is essential for applying bold, italic, and various other formatting options in UIWebview. My goal is to retrieve the position coordinates when a user interacts with the div tag using JavaScript/jQuery. I stumbled upon the required code on JSFiddl ...

Using JavaScript includes to verify the presence of various values

let colorSet = ["black", "red", "pink", ]; This is the colorSet array. I can easily check if a specific value is present in the colorSet array. For example, to check if "red" is present in the array, I can use the following code: let isRedPresent = color ...

Categorize an array by their names using Jquery and present them as a list

I have a list of cities and their corresponding countries structured like the following: { "data": [ { "cityname": "Newyork", "countryname": "USA" }, { "cityname": "amsterdam", "countryname": "Netherland" },{ "cityname": "Washington", "country ...

A guide on utilizing the Check All feature in nglightning for Angular 2

Is there a feature available in nglightning that allows users to check all records in a datatable? You can find the component at the following link: I am specifically looking for the ability to check all checkboxes in nglightning within the header row. Is ...

Updating the input value in a React application

With a list and an edit button, upon clicking the edit button, a new modal opens. How can I auto-populate the selected username email? The server-side response is {this.test.name}, where I provide him with the input value to auto-populate. However, when ...

Is there a way to make an input field mandatory in Gravity Forms by utilizing javascript or jquery?

I am currently in the process of developing a registration form for an upcoming event using gravity forms. The objective is to allow users to register only if the number of participants matches the number of available shirts. In case they do not match, the ...

Is it possible for PHP to accomplish this task?

Is it possible for PHP to achieve this? I have a set of arrays structured like this: $x[1][2][3] = 10; $x[1][2][4] = 5; $x[1][2][3] = 2; Upon using print_r($x), the output is: Array ( [1] => Array ( [2] => Array ...

Utilize a random file import with the help of React JS, Babel, and ES6

Having trouble displaying a random image using webpack. I have a directory with various images, such as: 1.jpg, 1-cropped.jpg 2.jpg, 2-cropped.jpg I want to fetch a random image from this directory without manually adding a reference for each file. I&apo ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

Utilizing Conditional Logic to Create a Dynamic Menu

I have a navigation menu on my website that is divided into two sections. There is a left panel and a right panel which slide in from the side when their respective buttons are clicked, covering the browser window. The functionality of sliding in the pan ...

What is the best way to retrieve combined reducers in react-redux?

I am currently experimenting with react-redux to manage states and props in a small project. Take a look at this example code: (Index.js) import React, { Component } from 'react' import { render } from 'react-dom' import { Provider ...

Implement Babel with node.js 6.9

It puzzles me why some folks opt to use Babel for their Node.js projects. I personally utilize node 6.9 and have no issues writing ES6 code - from default arguments in functions to arrow functions, rest parameters, and spread syntax. Do you think Babel is ...

What steps can I take to avoid res.send() from replacing the entire document?

When making an ajax call to insert users into the database, I want to handle the response in a specific way. If I use res.send() on the server side, it displays the response at the top left of a black document, which is not ideal. I attempted to use retu ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

I'm having trouble with my dropdown navigation menus - they keep popping back up and I can't seem to access

My website is currently in development and can be accessed at: The top navigation bar on the homepage functions properly across all browsers. However, there are three sections with dropdown submenus - About Us, Training, and Careers. These dropdown submen ...