Filtering and Displaying Unique City Names from an NSArray of NSDictionary Objects in Table Views

Filtering NSArray of NSDictionary Objects

Introduction

In this article, we will explore the process of filtering an NSArray of NSDictionary objects to remove duplicates based on a specific key-value pair. We will also delve into how to display only unique city names in a table view and show corresponding departments when a particular city is selected.

Background

An NSArray in Objective-C is a data structure that represents a collection of objects. A NSDictionary, on the other hand, is an unordered collection of key-value pairs where each key is unique and maps to a specific value. When working with arrays of dictionaries, it’s common to need to filter out duplicate entries based on a particular key.

Problem Statement

Given an array of dictionaries representing cities and their corresponding departments, we want to:

  1. Remove duplicates of city names from the array.
  2. Display only unique city names in the first table view.
  3. When a particular city is selected, show its corresponding department in the next table view.

Example Data

Let’s consider an example array of dictionaries with city and department information for India:

Array values :
{
    city = uk;
    department = "Sales support";
},
{
    city = us;
    department = "Sales support";
},
{
    city = italy;
    department = "Sales support";
},
{
    city = india;
    department = "x";
},
{
    city = india;
    department = "y";
},
{
    city = india;
    department = "z";
}

Solution Overview

To solve this problem, we will use a combination of the following techniques:

  1. Using an NSPredicate to filter out duplicate entries based on the city key.
  2. Utilizing an NSArray’s sortedArrayUsingComparator method to remove duplicates while preserving order.
  3. Implementing a didSelectRowAtIndexPath method to display departments corresponding to selected cities in a separate table view.

Step 1: Filtering Duplicates Using NSPredicate

To filter out duplicate entries based on the city key, we will use an NSPredicate. The predicate will be used to filter the responseArray and create a new array with only unique city names.

// Create a predicate that filters arrays containing specific values for "city"
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city == %@", [cityArray objectAtIndex:indexPath.row]];

However, since we’re using sortedArrayUsingComparator, the code should be modified as follows:

// Create an array with unique city names by comparing each object to others using a custom comparator
NSArray *uniqueCities = [responseArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    id value1 = [obj1 objectForKey:@"city"];
    id value2 = [obj2 objectForKey:@"city"];

    NSComparisonResult result = [value1 compare:value2];
    return (result == NSOrderedSame) ? NSOrderedSame : (result < 0) ? NSOrderedDescending : NSOrderedAscending;
}];

// Sort the array in ascending order to ensure predictable ordering
[uniqueCities sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    // Sort based on city name
    id value1 = [obj1 objectForKey:@"city"];
    id value2 = [obj2 objectForKey:@"city"];

    NSComparisonResult result = [value1 compare:value2];
    return (result == NSOrderedSame) ? NSOrderedSame : (result < 0) ? NSOrderedDescending : NSOrderedAscending;
}];

Step 2: Loading First Table View with Unique City Names

To display only unique city names in the first table view, we will use an NSArray’s sortedArrayUsingComparator method.

// Sort the array of dictionaries to ensure predictable ordering and remove duplicates based on the "city" key
NSArray *uniqueCityArray = [responseArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    // Compare objects using a custom comparator that checks if the city is the same
    id value1 = [obj1 objectForKey:@"city"];
    id value2 = [obj2 objectForKey:@"city"];

    NSComparisonResult result = [value1 compare:value2];
    return (result == NSOrderedSame) ? NSOrderedSame : (result < 0) ? NSOrderedDescending : NSOrderedAscending;
}];

// Load the first table view with unique city names
[self.tableView reloadData];

Step 3: Implementing didSelectRowAtIndexPath Method

To display departments corresponding to selected cities in a separate table view, we will implement a didSelectRowAtIndexPath method.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Get the selected city from the indexPath
    NSString *selectedCity = [uniqueCityArray objectAtIndex:indexPath.row];

    // Create an array predicate for filtering responses based on the selected city
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city == %@", selectedCity];

    // Filter the response array to get departments corresponding to the selected city
    NSArray *departments = [responseArray filteredArrayUsingPredicate:predicate];

    // Reload the second table view with the filtered departments
    [self.tableView2 reloadData];
}

Conclusion

In this article, we explored how to filter an NSArray of NSDictionary objects to remove duplicates based on a specific key-value pair. We also delved into how to display only unique city names in a table view and show corresponding departments when a particular city is selected.

By utilizing NSPredicate, NSArray’s sortedArrayUsingComparator method, and implementing a didSelectRowAtIndexPath method, we can efficiently manage data and provide a seamless user experience.


Last modified on 2024-03-13