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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
theDC
  • 6,364
  • 10
  • 56
  • 98

1 Answers1

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 }))
pacification
  • 5,838
  • 4
  • 29
  • 51