Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create arrays from a multidimensional array by each index object value

Here is an example of my main array:

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

And I want as output:

[
  ['Red', 'Black', 'White'],    // all values from first index of data array
  ['Small', 'Medium', 'Large'], // all values from second index of data array
  ['Good', 'Bad', 'Best']       // all values from third index of data array
]

I have tried with forEach , for...in, filter etc. But I did not success to get the previous output.

like image 327
Imran Avatar asked May 18 '26 13:05

Imran


2 Answers

You can use reduce() and then within the reduce loop use forEach(). In the forEach loop use the index to determine which array to push. It there's no value yet at that index, make a new array and push into that:

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

let arr = data.reduce((arr, item) => {            // look at each item in the data array
  item.data.forEach(({value}, index) => {         // look at each item in the item.data array
    (arr[index] || (arr[index] = [])).push(value) // create and array if necessary and push value into it
  })
  return arr
},[])

console.log(arr)
like image 99
Mark Avatar answered May 20 '26 04:05

Mark


You can also try as the below example shows.

filter() method is basically used when we want filtered output based on some conditions.

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' ] }
*/
like image 20
hygull Avatar answered May 20 '26 03:05

hygull



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!