Home > Blockchain >  Merge the first items in two different arrays into one - Javascript
Merge the first items in two different arrays into one - Javascript

Time:05-09

I want to merge the first items in two different arrays into one.

var arr = [];

var arr2 = [];

var year = ["January 2022", "February 2022", "March 2022", "April 2022", "May 2022"];

var value = [600000, 900000, 180000, 600000, 300000];

year.forEach(element => {
    arr.push({year: element});
});
                    
value.forEach(element2 => {
    arr2.push({value: element2});
});

The result I tried to achieve is this:

[
  {
    year: "January 2022",
    value: 600000
  }, {
    year: "February 2022",
    value: 900000
  }, {
    year: "March 2022",
    value: 180000
  }, {
    year: "April 2022",
    value: 600000
  }, {
    year: "May 2022",
    value: 300000
  }
];

So this is what I have tried but I am not getting the expected result yet:

var merged = arr.concat(arr2);

var newData = [];

merged.forEach(element => {
    newData.push({year: element.year, value: element.value});
});

console.log(newData);

CodePudding user response:

You could take an object with wanted keys and map the values for getting an array of objects.

This approach works for unlimited count of properties.

const
    getObjects = object => Object.entries(object).reduce((r, [k, a]) => a.map((v, i) => ({ ...r[i], [k]: v })), {}),
    year = ["January 2022", "February 2022", "March 2022", "April 2022", "May 2022"],
    value = [600000, 900000, 180000, 600000, 300000],
    result = getObjects({ year, value });

console.log(result);

CodePudding user response:

keeping with your logic I propose this:

var years = ["January 2022", "February 2022", "March 2022", "April 2022", "May 2022"];

var values = [600000, 900000, 180000, 600000, 300000];


function merger(years, values){
    if (years.length != values.length){
        console.log("Dog");
    }else {
        let merged = [];
        for(i=0; i < years.length; i   ){
            merged[i] = {year: years[i], value: values[i]};
        }
        return merged;
    }
}
console.log(merger(years, values));

it works!

CodePudding user response:

This will work if year array and value array has same length and same positions:

var year = ["January 2022", "February 2022", "March 2022", "April 2022", "May 2022"];

var value = [600000, 900000, 180000, 600000, 300000];

var result = [];


year.forEach((year, i) => result.push({year, value: value[i]}))


  • Related