How do I remove duplicates in NSMutableArray

Posted on 2008-11-05
Last Modified: 2013-11-25
I am not sure how to remove duplicate numbers in a NSMutableArray and whether to remove them before sorting or not.  And is there an easy way to remove duplicate numbers before they are even added to the array?  This is not homework.
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init];


    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];

    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];

    [numberFormatter setFormat:@"00"];

    NSString *myNumberString;

    NSMutableArray *array;

    int i;

    NSNumber *newNumber;

    NSNumber *numbersToPrint;

    printf ("\n");

    array = [[NSMutableArray alloc]init];

    // Initialize the random number generator.


    for (i = 0; i < 6; i++) {

        newNumber = [[NSNumber alloc]initWithInt:random() % 55 + 1];

        myNumberString = [numberFormatter stringFromNumber:newNumber];

        [array addObject:myNumberString];

        [array sortUsingSelector:@selector(compare:)];

        [newNumber release];


    // Using NSLog

    for (i = 0; i < 6; i++) {

        numbersToPrint = [array objectAtIndex:i];

        NSLog(@"The number at index %d is %@.", i, numbersToPrint);


    [array release];

    [pool drain];

    return 0;


Open in new window

Question by:barnwillyb
    LVL 5

    Accepted Solution

    You could use a NSMutableSet. A set can contain each value only once. Add random numbers until the set has the required size. And then copy it to an NSMutableArray (using NSEnumerator).

    However, this is only a useful approach if the number of random numbers is quite large. In your case the number of generated random numbers is very small. It is probably much easier and faster to iterate for each random number over the NSMutableArray to find the right position and to insert the new random number at the right position (using insertObject:atIndex:). This way it is also sorted (insert-sort) during creating.
    LVL 3

    Expert Comment

    Use insertion sort, find the location to insert using a binary search,

    insertion loop would look like this:

    start = 0
    end = array count
    if array empty
      add item, go to next item.
    1. search position = start + ((end - start) / 2), round down
    2. if insert item equals item at search position, exit search and go to next item to insert
    3. else if insert item is greater than the item at search position,
        if search position equals end
           insert at end
           start = search position + 1
    4. else
        if search position equals start
           insert before start
           end = search position
    5. if start equals end
        insert item after start.
    6. else
        go to 1

    so you get the insertion of a NSMutableSet, unique values and sorted, and save the need to copy.
    LVL 5

    Expert Comment

    @romanm, the binary search is only useful if there are more elements. With only 6 random numbers it will cause more overhead than benefit.
    LVL 3

    Expert Comment

    how will it cause more overhead then using a set?
    a set uses a binary search too, a set has a red-black tree balancing each time you insert, (I am talking windows but I think same applies).

    proposed algorithm is a shortcut over using a set, count of elements is irrelevent.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    This tutorial is posted by Aaron Wojnowski, administrator at  To view more iPhone tutorials, visit This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
    This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
    The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now