how to add two array values into one array in javascript

1568 views javascript
10

var period = ['1', '2', '3', '4'];
var marks = ['20', '15', '00', '20'];

i want result that is array in javascript // returns

data = [{"period": "1", "marks": 20},
{"period": "2", "marks": 15},
{"period": "3", "marks": 00},
{"period": "4", "marks": 20}];

I want to merge these arrays which are period and marks in to array called data thank you in advance

answered question

The posted question does not appear to include any attempt at all to solve the problem. StackOverflow expects you to try to solve your own problem first, as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a Minimal, Complete, and Verifiable example. For more information, please see How to Ask and take the tour.

1 Answer

8

Array.prototype.map()

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results

You can use map() like the following way:

var period = ['1', '2', '3', '4'];
var marks = ['20', '15', '00', '20'];

var data = period.map((d,i) => ({period:d, marks: marks[i]}));
console.log(data);

posted this

Have an answer?

JD

Please login first before posting an answer.