Pergunta

I am trying underscore.js for the first time and want to transpose my row array into column. As, I need to join it with 2D array

I checked discussion here and found can be done by _.zip.apply(). But, when I am trying it, it is not showing any reuslt

  Final = my 2D array
  dtr = ['s', 's', 'n'];

I need to join dtr with final such that every element in dtr is a column header in final array doing this:

  _.zip.apply(dtr, Final)

but it is not showing any result

expected outcome:enter image description here

my 2d array:-enter image description here

and the dtr array need to go at top of the 2d array.. hope it is clear.

Foi útil?

Solução

In case you want your dtr array to be the first array in the 2d array. One could do this:

var a = ['s','s','n'];
var b = [[50, 50, 50], 
         [50 , 5, 5],
         ['hello', 'beta', 'gama']];

var result = [a].concat(b);

Result:

[['s','s','n'],
 [50, 50, 50], 
 [50 , 5, 5],
 ['hello', 'beta', 'gama']];

Edit

var a = ['s','s','n'];
var b = [[50, 50, 'hello'], 
         [50,  5, 'beta'], 
         [50,  5, 'gama']];

var result = _.map(_.zip(a, b), _.flatten) 
// if native map support _.zip(a, b).map(_.flatten)

Result:

[['s', 50, 50, 'hello'], 
 ['s', 50,  5, 'beta'], 
 ['n', 50,  5, 'gama']];

Outras dicas

My answer contains two cases, which are dependent on how array b is organised.

Case one:

var a = ['s','s','n'];
var b = [[50, 50, 'hello'], 
         [50,  5, 'beta'], 
         [50,  5, 'gama']];

_.zip(a, b).map(_.flatten) // -> [Array[4], Array[4], Array[4]]

Case Two

var a = ['s','s','n'];
var c = [[50, 50, 50], 
         [50 , 5, 5],
         ['hello', 'beta', 'gama']];
var b = _.zip.apply(null, c); // content equals to case one variable b

_.zip(a, b).map(_.flatten) // -> [Array[4], Array[4], Array[4]]

Result:

[['s', 50, 50, 'hello'],
 ['s', 50,  5, 'beta'],
 ['n', 50,  5, 'gama']]
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top