Home > Blockchain >  Creating comma separated Array from an array and an object
Creating comma separated Array from an array and an object

Time:01-04

I have an array which has unique years and another json object which has year and value.

I want to create a comma separated array but push the year once and push the value against that year from a the json object.

Expected Output:

data= [
  { year:2015, value:[10,20,30]  }, 
  { year:2016, value:[50,60,70]  },
  { year:2017, value:[100,200,0] } 
] 

Inputs:

Unique = [2015,2016,2017]
data = [
  { Year: 2015, VALUE: 10 },
  { Year: 2015, VALUE: 20 },
  { Year: 2015, VALUE: 30 },
  { Year: 2016, VALUE: 50 },
  { Year: 2016, VALUE: 60 },
  { Year: 2016, VALUE: 70 },
  { Year: 2017, VALUE: 100 },
  { Year: 2017, VALUE: 200 },
  { Year: 2017, VALUE: 0 },
];

Code that I have tried:

let uniDs:any =[];
Unique.forEach((u) => {
  data.forEach((k) => {
    let x = uniDs.filter((x) => x.Year == u);
    if (x.length > 0) {
      x[0].value.push(k.VALUE);
    } else {
      uniDs.push({ Year: k.Year, value: [k.VALUE] });
    }
  });
});
console.log(uniDs);

Thanks In Advance.

CodePudding user response:

const Unique = [2015,2016,2017]
const data = [
  { Year: 2015, VALUE: 10 },
  { Year: 2015, VALUE: 20 },
  { Year: 2015, VALUE: 30 },
  { Year: 2016, VALUE: 50 },
  { Year: 2016, VALUE: 60 },
  { Year: 2016, VALUE: 70 },
  { Year: 2017, VALUE: 100 },
  { Year: 2017, VALUE: 200 },
  { Year: 2017, VALUE: 0 },
];

const result = Unique.map(
  year => ({
    year,
    value: data.filter(
      obj => obj.Year === year).map(
        obj => obj.VALUE
      )
    })
  )
console.log(result)

CodePudding user response:

You can filter your data based on unique array and then group the result on the year using array#reduce and extract all the values using Object.values().

const unique = [2015,2016,2017],
      data = [ { Year: 2015, VALUE: 10 }, { Year: 2015, VALUE: 20 }, { Year: 2015, VALUE: 30 }, { Year: 2016, VALUE: 50 }, { Year: 2016, VALUE: 60 }, { Year: 2016, VALUE: 70 }, { Year: 2017, VALUE: 100 }, { Year: 2017, VALUE: 200 }, { Year: 2017, VALUE: 0 },],
      result = Object.values(
               data.filter(({ Year }) => unique.includes(Year))
                   .reduce((r, { Year, VALUE}) => {
                      r[Year] = r[Year] || {year: Year, values: []};
                      r[Year].values.push(VALUE);
                      return r;
                   },{})
              );
console.log(result);

  • Related