Kayan
Kayan

Reputation: 51

Swift, how to use an array with indices to reorder another array

In Swift I have an array of indices that I want to use to permute an array of values (very easy to do in Matlab), but can't figure out a simple way of doing it (using a for-loop would be easy, but I'm looking for a more efficient method).

For example:

var indices = [1,0,2]
var values = ["A","B","C"]
var permute = values[indices]
// Hoping to print: permute = ["B","A","C"]

Upvotes: 3

Views: 329

Answers (4)

Bappaditya
Bappaditya

Reputation: 9642

An alternative solution using compactMap,

let indices = [1, 0, 2]
var values = ["A", "B", "C"]
let permute = indices.compactMap({ values[$0] })
print(permute)

Upvotes: 1

Abhishek Jain
Abhishek Jain

Reputation: 888

You can just map the keys array to the values array.

var keys = [1,0,2]
var values = ["a","b","c"]
print(keys.map({values[$0]}))

Upvotes: 0

Kathiresan Murugan
Kathiresan Murugan

Reputation: 2962

let indices = [1,0,2]
let values = ["A","B","C"]
var result: [String] = []

indices.forEach({ result.append(values[$0]) })
print(result) //["B", "A", "C"]

Upvotes: 0

prex
prex

Reputation: 739

var indices = [1,0,2]
var values = ["A","B","C"]
var permute = indices.map({values[$0]})
print(permute)

Upvotes: 8

Related Questions