Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array append() to return a new array

I'm working with a struct which has an array. I would like to add a new element to the array, however, the array is immutable so I can't simply append to it. Need to create a new array, append to it and then create a new structure with the extended array. (I know it sounds painful and memory intensive, but it is cleaner and more aligned with the Functional Programming paradigm.)

Is there an append() like function that doesn't mutate the array but instead returns a new one? This would be easier than having to declare a new array and appending to it.

like image 739
Daniel Avatar asked May 26 '16 06:05

Daniel


People also ask

Can I append an array to another array?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array.

Can you append to an array?

If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.

Can you append to an array in JavaScript?

Sometimes you need to append one or more new values at the end of an array. In this situation the push() method is what you need. This method accepts an unlimited number of arguments, and you can add as many elements as you want at the end of the array. The push() method also returns the new length of the array.


2 Answers

Would you not just add two arrays together?

let originalArray: [Type] = ...
let objectToAppend: Type = ...
let newArray = originalArray + [objectToAppend]


Or, in an extension, if you prefer:

extension Array {
    func arrayByAppending(o: Element) -> [Element] {
        return self + [o]
    }
}
like image 172
Max Chuquimia Avatar answered Oct 05 '22 03:10

Max Chuquimia


Try this:

extension NSArray {
    func myAppend(arrToAppend: NSArray) -> NSArray {
        let r : NSMutableArray = NSMutableArray(array: self)
        r.addObjectsFromArray(arrToAppend as [AnyObject])
        return r.copy() as! NSArray
    }
}

for a single object

extension NSArray {
    func myAppend2(objToAppend: AnyObject) -> NSArray {
        let r : NSMutableArray = NSMutableArray(array: self)
        r.addObject(objToAppend)
        return r.copy() as! NSArray
    }
}
like image 29
4oby Avatar answered Oct 05 '22 01:10

4oby