3

Let's say I have some numbers in an array like below

let numberArray = [1, 3, 4, 6, 9, 14, 16]

I know how to sum them all up by using reduce method but how can I start adding numbers from specific element. For example:

//Sum all up by reduce
let sumAll = numberArray.reduce(0, +)
//sumAll = 53 

//I want to start counting from the fourth element in the array which is 6
//so the total should be 45. [6 + 9 + 14 + 16]

What method should I use to achieve this?
Thanks in advance.

2 Answers 2

8

You can either use dropFirst(_:) or use a range as the index.

If it's not a fixed number, you could first use firstIndex(of:) to determine the index where you want to start.

numberArray.dropFirst(3).reduce(0, +)
numberArray[3...].reduce(0, +)
Sign up to request clarification or add additional context in comments.

1 Comment

dropFirst(3) is safer; it doesn't crash if numberArray has fewer than 3 elements.
4

Run reduce on the desired subarray:

let numberArray = [1, 3, 4, 6, 9, 14, 16]
let sum = numberArray[3...].reduce(0, +)

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.