Skip to content Skip to sidebar Skip to footer

What's The Objective-c Equivalent Of Js's `map()` Function?

What's the Objective-C equivalent of JS's map() function? Would I just use NSFastEnumeration and apply the function myself?

Solution 1:

You can use NSArray's enumerateObjectsUsingBlock: if you're on OS X 10.6 or iOS 4.:

NSMutableArray *mapped = [NSMutableArray arrayWithCapacity:[array count]];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    id mapObj = DoSomethingToObject(obj);
    [mapped addObject:mapObj];
}];

Solution 2:

It depends. If you have, say, an array of objects, and these objects have a URL property (for example), then you can do:

NSArray * urls = [myArray valueForKey:@"URL"];

Likewise, if you can trigger the behavior of the objects in question via a single message that takes 0 or 1 parameters, you can do:

[myArray makeObjectsPerformSelector:@selector(doFoo)];
//or:
[myArray makeObjectsPerformSelector:@selector(doFooWithBar:) withObject:aBar];

For anything beyond that, you'll have to iterate over the objects yourself. You can use a for() loop, a for(in) loop, or something like -enumerateObjectsUsingBlock:, etc.

Solution 3:

You do it yourself. There is no single method equivalent to what you want.

Edit: For those downvoting, this was the correct answer at the time (three years ago) and still is for Objective-C, but Swift does have a map() function.

Solution 4:

Check BlocksKit, it provides map, reduce and filer for NSArray.

  • (NSArray *)map:(BKTransformBlock)block;
  • (id)reduce:(id)initial withBlock:(BKAccumulationBlock)block;
  • (NSArray *)select:(BKValidationBlock)block;

Solution 5:

Category function for NSArray an alternative

- (NSArray *)map:(id(^)(id, BOOL *))block {
    NSMutableArray * array = [NSMutableArray array];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id newObject = block(obj,stop);
        if (newObject == nil) {
            newObject = [NSNull null];
        }
        [array addObject:newObject];
    }];
    return array.copy;
}

Category function for NSMutableArray an alternative

- (NSMutableArray *)map:(id(^)(id))block {
    NSEnumerator * enumerator = ((NSArray *)self.copy).objectEnumerator;
    id obj; NSUInteger idx = 0;
    while ((obj = enumerator.nextObject)) {
        self[idx] = block(obj) ?: [NSNull null];
        idx++;
    }
    returnself;
}

Post a Comment for "What's The Objective-c Equivalent Of Js's `map()` Function?"