How to create arrays from array
You could take a dynamic approach and get all items of the array after the key value for each new array.
var data = [[2011, 127072.7, 51584], [2012, 125920.3, 59974], [2013, 129305.4, 15468], [2014, 135364, 84554], [2015, 136757, 98754], [2016, 155653.5, 155548], [2017, 164130.5, 284848]],
[first, second] = data.reduce(
(r, [k, ...a]) => {
a.forEach((v, i) => r[i].push([k, v]));
return r;
},
Array.from({ length: Array.isArray(data[0]) ? data[0].length - 1 : 0 }, () => [])
);
console.log(first);
console.log(second);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use .map()
to iterate over your data and use some Array Destructuring to get the desired output:
const data = [
[ 2011, 127072.7, 51584 ],
[ 2012, 125920.3, 59974 ],
[ 2013, 129305.4, 15468 ],
[ 2014, 135364, 84554 ],
[ 2015, 136757, 98754 ],
[ 2016, 155653.5, 155548 ],
[ 2017, 164130.5, 284848 ]
];
const arr1 = data.map(([year, val]) => ([year, val]));
const arr2 = data.map(([year, _, val]) => ([year, val]));
console.log(arr1);
console.log(arr2);
.as-console-wrapper { max-height: 100% !important; top: 0; }