0

Google visualization API requires arrays like this:

var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);

I have separately array of columns

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];

for values

var values = [8.94, 10.49, 19.30, 21.45];

and for colors

var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.

0

4 Answers 4

6

Using Array#map.

var columns = ['Copper', 'Copper', 'Gold', 'Gold'],
    values = [8.94, 10.49, 19.30, 21.45],
    styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'],
    res = columns.map((v,i) => [v, values[i], styles[i]]),
    result = [['Element', 'Density', { role: 'style' }], ...res];
    console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

Sounds like you just need to immutably copy the array and then do whatever you want with it. Try this:

// ES6
var myArr = [1, 2, 3]
var newArr = [ ...myArr ]

// ES5
var myArr = [1, 2, 3];
var newArr = [].concat(myArr);

Comments

2

You can map them together, here is a working fiddle

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
var values = [8.94, 10.49, 19.30, 21.45];
var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

var newArr = columns.map((item, index) => {return [columns[index], values[index], styles[index]]})

console.log(newArr) //=> ['Copper', 8.94, '#b87333'],
                    //['Copper', 10.49, 'silver'],
                    //['Gold', 19.30, 'gold'],
                    //['Gold', 21.45, 'color: #e5e4e2' ],

Comments

1

ES6 solution using reduce function

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
var values = [8.94, 10.49, 19.30, 21.45];
var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

// Reduce all arrays to one vlaue
var result  = columns.reduce((acc, init, i) => {
    acc.push([init, values[i], styles[i]])
    return acc
}, [])


var out = [
         ['Element', 'Density', { role: 'style' }],
         ...result
      ]

console.log(out)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.