0

Im trying to figure out how to use highcharts with the dates. Im doing an API call and have in one variable clicks and in another variable the dates. I want to concatenate these 2 arrays but following the index.

For example

array1 = [timestamp1 , timestamp2, timestamp3]
array2 =[ clicks1, clicks2, clicks3 ]

I want to have then an array that is

data =  0: [timestamp1, click1],
        1: [timestamp2, click2],
        2: [timestamp3, click3]

I tried doing var data = array1.concat(array2);

but it concatenates in order

data = [timestamp1 , timestamp2, timestamp3 , clicks1, clicks2, clicks3 ]

my original code looks like this:


    getChartData(){
            axios.get("http://localhost:3003/desktop").then(api =>{
                const data = api.data;
              // console.log(data)

            var date =[];
                var clicks = []
                var impressions =[]

                for ( var i in data)
                {
                    date.push(data[i].Date)
                    clicks.push(data[i].Clicks)
                    impressions.push(data[i].Impressions)
                }



                var cd = date.concat(clicks);
                console.log(cd)

                 this.setState({
                    clicks:clicks,
                    date:date,
                    impressions:impressions,
                    cd: cd
                 })
            });




        }

This might be a very basic question, but I'm a beginner and could not find anything related.Any help would be appreciated.

Sundios
  • 418
  • 7
  • 20
  • Instead of pushing into `date` and `clicks`, why not push into `data` instead? – Scott Hunter Jul 10 '19 at 01:50
  • What you are looking for is called "Zipping", it is pretty common in languages such as Haskell. Somebody has already answered how to do it [here](https://stackoverflow.com/questions/22015684/how-do-i-zip-two-arrays-in-javascript). – Strong will Jul 10 '19 at 02:00

2 Answers2

2

You could parse all the keys of one of your array and then retrieve the value from both array using that key. Ex:

let output = []
Object.keys(array1).forEach((key) => {
    output.push(array1[key], array2[key]);
});

Here i'm using the forEach array function but you could achieve the same goal using a normal foreach loop.

Please note that this code is untested, it is just to show you the basic idea.

Nicolas
  • 8,077
  • 4
  • 21
  • 51
2

Assuming that both arrays are the same length you could use something like this. You can do the iteration a variety of ways.

const arr1 = ['a', 'b', 'c'];
const arr2 = ['A', 'B', 'C'];

const arrPaired = arr1.map((ent, i) => [ent, arr2[i]]);

console.log(arrPaired);