Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create arrays from array [closed]

I am a JavaScript beginner and I am trying make two different arrays with values from one main array.

My main array looks like:

0: Array(3) [ 2011, 127072.7, 51584 ] 1: Array(3) [ 2012, 125920.3, 59974 ] 2: Array(3) [ 2013, 129305.4, 15468 ] 3: Array(3) [ 2014, 135364, 84554 ] 4: Array(3) [ 2015, 136757, 98754 ] 5: Array(3) [ 2016, 155653.5, 155548 ] 6: Array(3) [ 2017, 164130.5, 284848 ] 

And i need create two arrays, first looking like:

0: Array(2) [ 2011, 127072.7] 1: Array(2) [ 2012, 125920.3] 2: Array(2) [ 2013, 129305.4] 3: Array(2) [ 2014, 135364] 4: Array(2) [ 2015, 136757] 5: Array(2) [ 2016, 155653.5] 6: Array(2) [ 2017, 164130.5] 

(first and second value)

and second like:

0: Array(2) [ 2011, 51584] 1: Array(2) [ 2012, 59974] 2: Array(2) [ 2013, 15468] 3: Array(2) [ 2014, 84554] 4: Array(2) [ 2015, 98754] 5: Array(2) [ 2016, 155548] 6: Array(2) [ 2017, 284848] 

(first and third value)

I trying splice, filter etc. but I don't know, how to start.

It is not necessary to write me an exact solution, but only steps how to do it.

like image 221
Dominik Lev Avatar asked Feb 10 '20 14:02

Dominik Lev


People also ask

How can you create an array in JavaScript using array literal?

Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

How do you remove the last entry of an array?

The pop() method removes (pops) the last element of an array. The pop() method changes the original array.


1 Answers

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; }
like image 50
Nina Scholz Avatar answered Sep 20 '22 03:09

Nina Scholz