How to feed curve() an array of points

I made a DataPoint object that has an x property and a y property. I generated an array of these and now want to draw a curve that takes the array as its argument. I tried something like the following:

 let s = ""
 for (let i = 0; i < idealCurve.length; i++){
      let x = idealCurve[i].x;
      let y = idealCurve[i].y;
      s = s + Number(x) + "," + Number(y) +","
    }
    s=s.slice(0, -1)
    }
curve(s);

This doesn’t work.
p5.js says: curve() was expecting at least 8 arguments, but received only 1.
Is there a way to feed curve() the array or cast the sequence of numbers and commas appropriately?

The curve() function expects a discrete set of arguments, not a string containing values delimited by commas. For example:

// This would work
curve(0,0, 10,0, 5,20, 20,20);

// This would not work
curve("0,0,10,0,5,20,20,20");

In your case, since you are trying to invoke the curve() function with an array of values extracted from objects stored in an array, you can use an array to store the arguments, and then apply the spread operator:

// Assuming idealCurve contains 4 points, since the curve function
// requires 4: a start, an end, and two control points in between.
let args = [];
for (let i = 0; i < idealCurve.length; i++){
  args.push(idealCurve[i].x, idealCurve[i].y);
}
curve(...args);
1 Like

You can collect all properties x & y from array idealCurve[] as 1 array sequence of numbers by calling method Array::flatMap() like this:
const curveArgs = idealCurve.flatMap(({ x, y }) => [ x, y ]);

Then pass that flattened array to curve() using the spread operator ...:
curve(...curveArgs);

Thank you KumuPaul and GoToLoop for your help.
I ended up doing the following:

 curve.apply(null,idealCurve.slice(0,8))

I did not look closely enough at the documentation for curve(); I though I could feed it more than four points. Once I realized I had to make a long curve from a series of segments, I adopted a different strategy altogether.

I don’t get how the statement above can successfully run. :dizzy_face:

Unless you’ve later changed the datatype of array idealCurve[] from an object of { x, y } properties (like we can assume from your original posted code) to just number values. :wink:

Regardless the spread operator ... is much simpler than using methods Function::apply() + Array::slice(): curve(...idealCurve) :sunglasses: