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.
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.
4 Answers
Reset to default 6Using 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);
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);
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' ],
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)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744301777a4567536.html
评论列表(0条)