My data array is a 2d array and each inner array holds data in the form [date, color]. I am trying to graph the dates and the colors and to do this I am trying to map the elements in the inner array. However, my current map function does not work when I try mapping two elements at once. How can I fix this?
shapes: data.map((date, type_color) => ({
x0: date,
y0: 0,
x1: date,
y1: 1,
opacity: 0.8,
line: {
color: type_color,
width: 3,
dash: 'dot'
}
}))
I think you mean to be using destructuring, but you aren't; you're just accepting two separate parameters in your map callback. When you do that, the first will be the [date, color] array (each element from the data array); the second will be the index of the element in data.
To use parameter destructuring, you'd use [date, type_color] in the parameter list:
shapes: data.map(([date, type_color]) => ({
// ^ ^
x0: date,
y0: 0,
x1: date,
y1: 1,
opacity: 0.8,
line: {
color: type_color,
width: 3,
dash: 'dot'
}
}))
That applies [date, type_color] destructuring to the first parameter.
const data = [
["date1", "color1"],
["date2", "color2"],
["date3", "color3"],
];
const result = {
shapes: data.map(([date, type_color]) => ({
// ^ ^
x0: date,
y0: 0,
x1: date,
y1: 1,
opacity: 0.8,
line: {
color: type_color,
width: 3,
dash: 'dot'
}
}))
};
console.log(result.shapes);
.as-console-wrapper {
max-height: 100% !important;
}