How to push element in array in a certain structure

๐Ÿ‘:1

You can pass an empty array as initial value for reduce method instead of 0 and instead of adding the value you can insert the value into the array and return that array.

var data={appNamesLables,datasets: [] };

var backgroundColorSGreen='#318CE7'
var backgroundColorRed='#FF8C00'
var backgroundColorYellow='#F49AC2'
var lebel1='Green'
var lebel2='Red'
var lebel3='Yellow'

for (let i = 0; i < appNamesLables.length; i++)
{
  var strToMatch=appNamesLables[i]
  //@ts-ignore
  const matches = Object.values(products).filter(s =>s.Name.toString().includes(strToMatch)); 
var green = matches.reduce(function (n, comp) {
     //@ts-ignore
    return [...n, parseInt(comp.statusGreen)];
  }, []);

var red = matches.reduce(function (n, comp) {
    //@ts-ignore
   return [...n, parseInt(comp.statusRed)];
 }, []);

 var yellow = matches.reduce(function (n, comp) {
  //@ts-ignore
 return [...n, parseInt(comp.statusYellow)];
}, []);


}

//Here I need to push element
  data.datasets.push({
     label: label1,
     backgroundColor: backgroundColorSGreen,
     data: green,
  })

  data.datasets.push({
     labe: label2, 
     backgroundColor: backgroundColorRed, 
     data: red })

  data.datasets.push({
     labe: label3, 
     backgroundColor: backgroundColorYellow, 
     data: yellow 
  })

Instead of reduce you can use map as well like this,

var green = matches.map(item => item.statusGreen);
var red = matches.map(item => item.statusRed);
var yellow = matches.map(item => item.statusYellow);

This will be much cleaner.

Leave a comment