Skip to content
Advertisement

How to combine 2 arrays in a way that 1st element of array1 and 1st element of array2 and so on form a new array

I have 2 arrays. The first contains the years like [2021,2020,2019,2018,2017] and the second contains number of occurrence like [2,3,1,3,3] I want the new array to look like this [[2021,2],[2020,3],[2019,1],[2018,3],[2017,3]] How to do this? Please help! Thank you in advance.

UPDATE:

const merge = (y, o) => {
    const res = [];
    y.forEach((year, i) =>
              res.push(`${year},${o[i]}`)
             );
    return res;
  };
  console.log(merge(allyears,farray))

I tried doing this and it works fine but the new array looks like this

["2021,3","2020,1","2019,2","2018,3","2017,3"]

How to make it look this way

[[2021,2],[2020,3],[2019,1],[2018,3],[2017,3]]

Advertisement

Answer

Make sure that the length of 2 arrays is equal

So we have:

const arr1 = [2021,2020,2019,2018,2017];
const arr2 = [2,3,1,3,3];

const combine = arr1.map((value, index) => ([value, arr2[index]]))

console.log(combine)

P/s: There are some other solutions that you can use, but only that one above

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement