0

What is the best way to merge two arrays into one array of objects, ie: I have two arrays:

dates = ['2020-01-01', '2020-01-15', '2020-02-01'];
values = [0.1, 0.4, 0.8];

and I want to assign to another variable this:

someData = [['2020-01-01', 0.1], ['2020-01-15', 0.4], ['2020-02-01', 0.8]];

edit: I'm courios if there is any more elegant solution than this:

const someData;
this.dates.forEach((value, i )=>{
  someData.push([dates[i]],value);
})
Adrian
  • 482
  • 5
  • 20

4 Answers4

1

const dates = ['2020-01-01', '2020-01-15', '2020-02-01'];
const values = [0.1, 0.4, 0.8];

const result = dates.map((x,i) => new Array(x, values[i]));
console.log(result);

Using a map to iterate through the dates and return a new array along with values in it. Hope this helps!

rcoro
  • 326
  • 6
  • 12
Ram Sankhavaram
  • 1,218
  • 6
  • 11
1

const dates = ['2020-01-01', '2020-01-15', '2020-02-01'];
const values = [0.1, 0.4, 0.8];
const newArray = dates.map((item,index) => [item,values[index]]);
console.log(newArray);
1

If you want an elegant solution, take inspiration from Haskell's zip.

function zip(arr1, arr2) {
    return arr1.map((k, i) => [k, arr2[i]]);
}

const someData = zip(dates, values).
Rubydesic
  • 3,386
  • 12
  • 27
0

you are really just creating an array of arrays. Consider:

var dates = ['2020-01-01', '2020-01-15', '2020-02-01'];
    var values = [0.1, 0.4, 0.8];
    var theArray=[];
    for(let i=0;i<dates.length;i++){
        var littleArray=[];
        littleArray.push(dates[i],values[i]);        
        theArray.push(littleArray);
     }

    console.log(theArray);
DCR
  • 14,737
  • 12
  • 52
  • 115