1

Let say I have an array:-

var arr = [0,1,2,3,4]

I need to pass only "1" and "4" to function below

function func1(onlyArray){
     //Do Stuff...
}

I have tried both but both also dont work

func1(arr[1,4])
func1(arr[[1],[4]])

Can anyone show me the right way or give me some keyword?

6
  • 2
    func(arr[1], arr[4]) Commented Oct 10, 2017 at 19:38
  • @wostex but the function only accept one parameter, will this detect as two parameter? Commented Oct 10, 2017 at 19:40
  • @vbnewbie, use this: func([arr[1], arr[4]]) Commented Oct 10, 2017 at 19:41
  • What is the type of the parameter? Commented Oct 10, 2017 at 19:41
  • Do you have control over the function or are you locked into it only accepting a single argument? If you can't change the function, how will the function know how many parameters it's receiving? Commented Oct 10, 2017 at 19:43

3 Answers 3

6

You can use this: func([arr[1], arr[4]])

We are taking the elements at index 1 and 4 of the array arr and creating a new array with those elements. Then we pass that newly created array to func.

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

Comments

1

If you need a single array instead of 2, use this:

var arr = [0,1,2,3,4];

function func1(onlyArray){
     //Do Stuff...
    console.log(onlyArray); // [1, 4]
}

func1(arr.filter((item,index) => index === 1 || index === 4));

5 Comments

[arr[1], arr[4]] is much simpler, why not just use that ?
@Taurus, he just provided another solution.
@Alexandru-IonutMihai Oh
@Taurus, I've included an optional way to get a single array. Yours works as well.
I think this better fits the op's question. Since you want to pass a single array consisting only of 1 and 4.
0

So using your array:

var arr = [0,1,2,3,4];

and your function:

function myFunction(newArr){ //Do stuff console.log(newArr); };

You can wrap the array indexes you want to use inside of their own array when you call the function, like the following:

myFunction([arr[1], arr[4]]); //Output is [1, 4]

3 Comments

How is this different than @Taurus's answer?
It isn't. Their answer is more brief and earlier than my comment. This is my first time trying to help on StackOverflow, so I spent more time learning how to use the markup than I really did responding. Sorry, my friend.
No problem - thanks for the explanation, and your willingness to help!

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.