1

I have two arrays and I need to create objects like {x: new Date(2019, 1, 1), y: 0} The result of my arrays looks like this

dates

Array [
  "2019, 1, 31",
  "2019, 2, 28",
  "2019, 3, 31",
]

monthlyTopUp

Array [
  0,
  50,
  0,
]

Now each index from first array needs to match the index from second array.

What I've tried returned me an array with other arrays inside

Array [
  Array [
    "2019, 1, 31",
    0,
  ],
  Array [
    "2019, 2, 28",
    50,
  ],
  Array [
    "2019, 3, 31",
    0,
  ],
]

The way I've done this:

const array = [dates, monthlyTopUp];
const data = array.reduce(
  (dates, topUp) => topUp.map((v, i) => (dates[i] || []).concat(v)), []
);
console.log(data)
3
  • Seems like you have a solid groundwork, what have you tried? Commented Mar 6, 2019 at 15:49
  • i suggest array.map Commented Mar 6, 2019 at 15:51
  • @LiamMacDonald I am getting the last day of each month in a year then I calculate the total topUp transactions for each month. So now I need to make a graphic representation of this thats why I need to create objects in this format {x: new Date(2019, 1, 1), y: 0} Commented Mar 6, 2019 at 15:53

3 Answers 3

2

You can simply do it like this:

var arr1 = ["2019, 1, 31",  "2019, 2, 28",  "2019, 3, 31"];
var arr2 = [0, 50, 0];

var result = [];

for(var i = 0; i < arr1.length; i++){
    result.push({'x':arr1[i], 'y':arr2[i]});
}

console.log(result);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Array.prototype.reduce

let arr1 = ["2019, 1, 31",  "2019, 2, 28",  "2019, 3, 31"];
let arr2 = [0, 50, 0];

let final=arr1.reduce((acc,value,i)=>{
let tempobj={};

tempobj["x"]=new Date(value.replace(/\s/g, "").replace(/,/g, "-"));
tempobj["y"]=arr2[i];
acc.push(tempobj)
return acc;


},[])

console.log(final)

Comments

1

Or array.map

var arr1 = ["2019, 1, 31",  "2019, 2, 28",  "2019, 3, 31"];
var arr2 = [0, 50, 0];

var result = arr1.map((v, k) => {return {x:v,y:arr2[k]}})

console.log(result);

https://jsfiddle.net/fgo5wanh/

2 Comments

It would be better if you add a working fiddle too .
I added the fiddle now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.