0

I'd like to create an array that contains elements from another array multiplied by some Int value.

Example:

the following code

let arr = [1,2,3]
let multiplier = 3
print(function(arr, multiplier))

should return

[1,2,3,1,2,3,1,2,3]

I know how to make it using nested for loops, but I'm looking for some nifty functional way. I was thinking about map() function, but it iterates over each element of a given array, which is not my use case I suppose.

3

1 Answer 1

1

Main idea:

  1. Create array of arrays,
  2. flatMap to one-dimensional array.

Example:

let arr = [1, 2, 3]
let multiplayer = 3
print(Array(repeating: arr, count: multiplayer).flatMap({ $0 }))
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.