1

I am having a with graph, i need to remove duplicates values from array and "0" as well and i want to adjust array according to that for example


extension Array where Element: Equatable {
 var unique: [Element] {
 var uniqueValues: [Element] = []
 forEach { item in
 if !uniqueValues.contains(item) {
 uniqueValues += [item]
 }
 }
 return uniqueValues
 }
}
let speed = [0, 10, 20, 20, 40, 50, 50 ,50, 80, 90, 100]
let time = ["9", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20"]
speed.unique // Return Only Unique Values 

Now i want my time array to be updated. Example Index : 0, 3 - is removed from speed i want to remove index 0, 3 from time as well

asked May 10, 2019 at 3:09
3
  • Use one array of struct where the struct has speed and time properties. Then you much more easily sort and filter the array of struct. When done you could create the two final arrays from the final array of struct. Commented May 10, 2019 at 3:36
  • i am using speed as struct and time as [String], but no luck :( Commented May 10, 2019 at 3:39
  • Please read my comment again. You want one struct with both values and a single array. Commented May 10, 2019 at 3:41

1 Answer 1

2

You can do it this way:

let speed = [ 0, 10, 20, 20, 40, 50, 50, 50, 80, 90, 100]
let time = ["9", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20"]
var sp = [Int]()
var tm = [String]()
for (i, x) in speed.enumerated() {
 if !sp.contains(x) {
 sp.append(x)
 tm.append(time[i])
 }
}
print(sp) //[ 0, 10, 20, 40, 50, 80, 90, 100]
print(tm) //["9", "10", "11", "13", "15", "18", "19", "20"]

Choosing an appropriate type for time is advisable.

It is recommended in object-oriented programming to have speed and time as properties of a struct:

struct Mover {
 let speed: Int
 let time : TimeInterval
}

For example given this array:

let movers = [Mover(speed: 0, time: 9),
 Mover(speed: 10, time: 10),
 Mover(speed: 20, time: 11),
 Mover(speed: 20, time: 12),
 Mover(speed: 40, time: 13),
 Mover(speed: 50, time: 15),
 Mover(speed: 50, time: 16),
 Mover(speed: 50, time: 17),
 Mover(speed: 80, time: 18),
 Mover(speed: 90, time: 19),
 Mover(speed: 100, time: 20)]

You could keep the elements with a unique speed this way:

var speeds = Set<Int>()
let moversUniqueSpeed = movers.filter { speeds.insert(0ドル.speed).inserted }
answered May 10, 2019 at 3:46

1 Comment

i am so dumb why didn't i thought about this, Thank you very much.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.