skip to Main Content

I’m working on a chart with the following array of objects.

 var probeData = [ { min: 0.02, max: 1.44, avg: 0.73 },
                   { min: 0.06, max: 1.57, avg: 0.76 } ]

And the callback below.

generateLabels: (_chart) => {
  return probeData.map((obj, i) => ({
    text: `UCL ${i+1} ${obj.max}`,
    index: i,
  })
);

Now, instead of returning only the max, I need to return, for each object also min and avg.

I tried the following solution but the callback returns only the two avg instead of the 6 values.

generateLabels: (_chart) => {
  return probeData.map((obj, i) => ({
    text: `UCL ${i+1} ${obj.max}`,
    index: i,
  },
  {
    text: `LCL ${i+1} ${obj.min}`,
    index: i,
  },
  {
    text: `AVG ${i+1} ${obj.avg}`,
    index: i,
  }) 
);

enter image description here
What am I missing here?

2

Answers


  1. you are probably looking for flatMap

    const probeData = [ { min: 0.02, max: 1.44, avg: 0.73 },
                       { min: 0.06, max: 1.57, avg: 0.76 } ]
                       
    const res =  probeData.flatMap((obj, i) => [{
        text: `UCL ${i+1} ${obj.max}`,
        index: i,
      },
      {
        text: `LCL ${i+1} ${obj.min}`,
        index: i,
      },
      {
        text: `AVG ${i+1} ${obj.avg}`,
        index: i,
      }]) 
      
    console.log(res)
    Login or Signup to reply.
  2. You are accidentally using the comma operator, but want to map one item to multiple objects. Try Array.flatMap(), as cmgchess shows.


    The comma operator is a comma-separated list of expressions which evaluates to its last expression. In your case, the previous object initializations are therefore unused.

    To return multiple objects in JavaScript, try returning them as part of another object (e.g. an array).

    It seems you’d want to afterwards flatten the resulting array of arrays. Instead of calling Array.map() followed by Array.flat(), JS provides Array.flatMap() for convenience.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search