supersize
supersize

Reputation: 14773

select multiple array elements at once

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?

Upvotes: 3

Views: 2817

Answers (2)

tommyleejones
tommyleejones

Reputation: 347

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))

Upvotes: 0

Meredith
Meredith

Reputation: 840

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.

Upvotes: 2

Related Questions