3

a very basic Array question but I don't know how to do this in the best possible way.

I have an array

var pathArr = [element1, element2, element3, element4, element5, element6]

what can I do if I want to select multiple elements of this path at once.

Lets say:

pathArr[0-2].dofunction()

in this example I'm doing the function on the first three elements.

or

pathArr[1,6].dofunction()

in this example only on element1 and element6

Is there something I can do with an array?

2 Answers 2

2

No.

Iterate through your array and apply your method to each appropriate item.

You could use slice to return a range of items in an array, which might make it easier for you, depending on what you're doing.

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

1 Comment

Should note that slice is only helpful for the first example, since the elements are a contiguous subsequence.
0

Nowadays you can solve this easily with the following one liners:

pathArr.slice(0,2).forEach(x=>dofunction(x))

To select multiple elements from the array you can use a map function, like so:

[1,6].map(x=>pathArr[x]).forEach(x=>dofunction(x))

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.