0

I have an array of strings that I pull from the web in any assortment of colors:

var colors = ["red", "green", "yellow", "blue", "purple"]

but it also might come as:

//this time less colors
var colors = ["yellow", "red", "purple"]

No matter which way they come in I want to sort through the colors array and add them to a new array and I want the new array to have this order:

//the way I want the new array to have it's elements
["red", "purple", "pink", "yellow", "brown", "blue", "orange", "green"]

I tried:

var newArr:[String] = []

for color in colors{

  if color == "red"{
    newArr[0] = "red"
  }
  if color == "purple"{
    newArr[1] = "purple"
  }
  if color == "pink"{
    newArr[2] = "pink"
  }
  if color == "yellow"{
    newArr[3] = "yellow"
  }
  if color == "brown"{
    newArr[4] = "brown"
  }
  if color == "blue"{
    newArr[5] = "blue"
  }
  if color == "orange"{
    newArr[6] = "orange"
  }
  if color == "green"{
    newArr[7] = "green"
  }
}

I got an exception:

fatal error: Index out of range

I know where I made the out of range mistake at but I can't figure out how to get it to put it in the order I want.

How can I loop through the colors array and take whatever elements are inside of it and add them to a new array in the order I want?

Lance Samaria
  • 17,576
  • 18
  • 108
  • 256

1 Answers1

4

Here's one possible solution - filter the master list of colors based on the colors you actually have.

let masterColors = ["red", "purple", "pink", "yellow", "brown", "blue", "orange", "green"]
var colors = ["yellow", "red", "purple"] // whatever colors you have
var newArr = masterColors.filter { colors.contains($0) }
rmaddy
  • 314,917
  • 42
  • 532
  • 579