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:
JavaScript
x
9
1
const merge = (y, o) => {
2
const res = [];
3
y.forEach((year, i) =>
4
res.push(`${year},${o[i]}`)
5
);
6
return res;
7
};
8
console.log(merge(allyears,farray))
9
I tried doing this and it works fine but the new array looks like this
JavaScript
1
2
1
["2021,3","2020,1","2019,2","2018,3","2017,3"]
2
How to make it look this way
JavaScript
1
2
1
[[2021,2],[2020,3],[2019,1],[2018,3],[2017,3]]
2
Advertisement
Answer
Make sure that the length of 2 arrays is equal
So we have:
JavaScript
1
6
1
const arr1 = [2021,2020,2019,2018,2017];
2
const arr2 = [2,3,1,3,3];
3
4
const combine = arr1.map((value, index) => ([value, arr2[index]]))
5
6
console.log(combine)
P/s: There are some other solutions that you can use, but only that one above