Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of objects array [duplicate]

Tags:

arrays

ios

swift

I can't figure out how to find index of object in array. For example I have this data structure:

class Person {
var name: String
var age: Int

init(name personName: String, age personAge: Int) {
    self.name = personName
    self.age = personAge
  }
}

let person1 = Person(name: "person1", age: 34)
let person2 = Person(name: "person2", age: 30)
...
var personsArray = [person1, person2, ...]

I tried to use personsArray.index(where: ....) but I don't understand how to use it. index(of: ...) doesn't work. I think because personsArray doesn't conform to Equatable protocol...

like image 299
Alex_slayer Avatar asked Apr 26 '17 08:04

Alex_slayer


People also ask

How do you find the index of duplicate elements in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate.All such elements are returned in a separate array using the filter() method.

How do you check if there are duplicate elements in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = i+1; j < myArray. length; j++) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } return false; // means there are no duplicate values. }

Can index have duplicates?

Duplicate indexes are those that exactly match the Key and Included columns. That's easy. Possible duplicate indexes are those that very closely match Key/Included columns.

How do you filter out duplicates in array of objects?

To remove the duplicates from an array of objects: Create an empty array that will store the unique object IDs. Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.


1 Answers

index(of: )

gets the Person in your case - it is generic function.

index(where: ) 

gets the condition for which you want to find particular Person

What you could do:

personsArray.index(where: { $0.name == "person1" })

Or you could send object to:

personsArray.index(of: existingPerson)

For both options you could get nil - you will have to check it for nil (or guard it).

like image 105
Miknash Avatar answered Sep 29 '22 22:09

Miknash