2

I have a CSV file of some data and for each line, I split it by the comma to get an array vals.

Now I want to pass vals into a function, but "flatten" it (without changing the function because it is used elsewhere)

function foo(x, y, z) {
     return x*y*z:
}
    
var vals = [1, 3, 4];
//want a shortcut to this (this would be a nightmare with like 20 values)
foo(vals[0], vals[1], vals[2]);

Edit:
Sorry, kind of left out a big detail. I only want part of the array, like the first 10 elements of a 12 element array. Any shortcut for this?

1
  • In JavaScript, you don't need to specify var for the arguments. function foo(x, y, z) works fine. Commented Dec 30, 2020 at 7:21

2 Answers 2

4

Use Spread operator; if you are using es6.

var vals = [1,2,34,5]
foo(...vals)

Or you could also use apply

function foo(a,b,c,d,e) {
  console.log(a,b,c,d,e)
}
var vals = [1,2,3,4,5]
foo.apply(null, vals)

Sign up to request clarification or add additional context in comments.

Comments

0

first you don't need var in the parameters,

second, you may use the spread operator

function foo(x, y, z) {
  return x * y * z;
}
var vals = [1, 3, 4];
console.log(foo(...vals));

reference: spread operator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.