# Remove an element from an array without changing the original

I want to delete a element from an array without changing the original. Like this:

``````original_array = [12,13,14,15]
new_array = function_to_delete_a_element(element_to_delete = 14, array = original_array)
print(new_array)
>[12,13,15]
print(original_array)
>[12,13,14,15]  #Here, all the functions that I have looked for to eliminate, change the original array, I want to keep it
``````

Above is what I want to do, but all the functions I have found also remove the element from the original array, and when i print the original array, throw this:

``````print(original_array)
>[12,13,15] # I want to get this ---> [12,13,14,15]
``````

Yes, it seems that it is as you describe. You can do:

``````julia> a=[1,2,3]
3-element Vector{Int64}:
1
2
3

julia> b=deleteat!(deepcopy(a),2)
2-element Vector{Int64}:
1
3

julia> a
3-element Vector{Int64}:
1
2
3

julia> b
2-element Vector{Int64}:
1
3
``````

`julia> b=deleteat!(copy(a),2)`

Is enough in this case.

1 Like

Why not just:

``````@views deleteelem(i, a::AbstractVector) = vcat(a[begin:i-1], a[i+1:end])
``````

to return a new array with index `i` removed.

3 Likes

Ok, but how do I do it indicating the particular element and not the index? Like this:

``````a =[12,13,14]
b=deleteat!(deepcopy(a),13)
``````

PD: How do you write the code for Julia here? Maybe you want `filter`?

``````julia> filter(!=(14), [12,13,14,15])
3-element Vector{Int64}:
12
13
15
``````
5 Likes

Call `findfirst(==(13), a)` to get the index of the first time it appears? Or use `filter` (which removes all occurrences of a particular value).

Or use some other data structure (e.g. `Set`) that is addressed by value.

2 Likes