---
title: "filtering NSArray into a new NSArray in objective-c"  
description: "filtering NSArray into a new NSArray in objective-c"  
author: "Anonymous User"  
published: 2015-08-22  
updated: 2015-08-22  
canonical: https://www.mindstick.com/forum/33424/filtering-nsarray-into-a-new-nsarray-in-objective-c  
category: "iphone"  
tags: ["iphone", "ios", "objective c"]  
reading_time: 1 minute  

---

# filtering NSArray into a new NSArray in objective-c

I have an NSArray and I'd like to create a new NSArray with [objects](https://www.mindstick.com/forum/145447/what-are-objects) from the original [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net) that meet [certain criteria](https://www.mindstick.com/articles/12944/mattresses-for-kids-and-mothers-should-meet-certain-criteria-issues-you-should-consider). The criteria is decided by a [function that returns](https://www.mindstick.com/forum/157562/what-is-a-function-in-sql-create-a-function-that-returns-stu_name-when-passed-stu_id) a BOOL.

I can create an NSMutableArray, iterate through the [source](https://www.mindstick.com/interview/840/what-happens-if-the-both-source-and-destination-are-named-same) array and [copy](https://www.mindstick.com/forum/161993/explain-the-numpy-array-copy-vs-view-with-example) over the objects that the [filter](https://www.mindstick.com/forum/1176/filter-in-a-xml-file-in-c-sharp) function accepts and then create an [immutable](https://www.mindstick.com/interview/2439/how-to-create-immutable-class) [version](https://www.mindstick.com/articles/12845/things-to-remember-while-migrating-odoo-to-a-better-version) of it.

Is there a better way?

## Replies

### Reply by Tarun Kumar

NSArray and NSMutableArray provide methods to filter array contents. NSArray provides filteredArrayUsingPredicate: which returns a new array containing objects in the receiver that match the specified predicate. NSMutableArray adds filterUsingPredicate: which evaluates the receiver’s content against the specified predicate and leaves only objects that match. These methods are illustrated in the following example.

```
NSMutableArray *array =  [NSMutableArray  arrayWithObjects:@"Bill", @"Ben",                @"Chris", @"Melissa", nil];
NSPredicate  *bPredicate = [NSPredicate predicateWithFormat:           @"SELF beginswith[c] 'b'"];
NSArray *beginWithB =  [array filteredArrayUsingPredicate:bPredicate];

// beginWithB contains { @"Bill", @"Ben" }.
NSPredicate *sPredicate =  [NSPredicate predicateWithFormat:                @"SELF contains[c] 's'"];
[array  filterUsingPredicate:sPredicate];

// array now contains { @"Chris", @"Melissa" }
```


---

Original Source: https://www.mindstick.com/forum/33424/filtering-nsarray-into-a-new-nsarray-in-objective-c

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
