# How do I calculate an array of differences?

Given an array: `[1,3,6,8]`

How would I create the array `[1,2,3,2]` ? (i.e. `[1, 3-1, 6-3, 8-6]`)

• How to conform to CBCentralManagerDelegate Protocol? (Swift IOS)
• IOS pushViewController without tabBar and navigationBar
• UIButton Target Action inside UIView
• Can't convert value of type - Swift
• How to get a list of column names with Sqlite.swift?
• I want to Switch Time scrubber to do 15 min intervals
• I wrote some stupidly complex code that just crashes. I want to use the `map`, or `reduce` functions to make the array compute expression really nice and short.

Help ? I know this is simple but I just don’t know how to do it.

### 3 Solutions Collect From Internet About “How do I calculate an array of differences?”

Sure, you can use `map` to do this fairly easily. You just have to keep track of the item before the current one.

Something like this should do the trick:

``````// your array
let arr = [1, 3, 6, 8]

// a variable to keep track of the previous item
var previousItem = 0
let arrOfDifferences:[Int] = arr.map {item in // the current item
defer {previousItem = item} // set the previous item to the current one, after the return happens
return item-previousItem // return the difference
}

print(arrOfDifferences) // [1, 2, 3, 2]
``````

You can “zip” the array with a shift of itself and map the result
to the differences:

``````let numbers = [1,3,6,8]
let diffs = numbers.prefix(1) + zip(numbers, numbers.dropFirst()).map { \$1 - \$0 }
print(diffs) // [1, 2, 3, 2]
``````

Explanation:

• `numbers.prefix(1)` returns a sequence with the initial array
element.
• `numbers.dropFirst()` is a subsequence of all elements but the first,
in this case `3, 6, 8`.
• `zip(...)` creates a sequence of pairs, stopping when the shorter
input sequence is exhausted, in this case `(1, 3), (3, 6), (6, 8)`.
• `map { \$1 - \$0 }` maps this sequence of pairs to an array of the
element-wise differences, in this case `2, 6, 3`.

Here’s a solution using `reduce`:

``````[1,3,6,8].reduce(([], 0)) {
(\$0.0 + [\$1 - \$0.1], \$1)
}.0 // [1,2,3,2]
``````

Edit: here’s another solution with `reduce` that probably will perform better:

``````var differences = [Int]()
[1,3,6,8].reduce(0) {
differences.append(\$1 - \$0)
return \$1
}
// differences is now [1,2,3,2]
``````