https://kotlinlang.org logo
Title
f

frogger

01/21/2020, 10:12 AM
what is the ideomatic way to get a copy of an Array without element
n
?
e

Egor Okhterov

01/21/2020, 10:17 AM
val array = arrayOf(1, 2, 3)
val slice = array.dropLast(1)
f

frogger

01/21/2020, 10:23 AM
I don't think so @Egor Okhterov:
Returns a list containing all elements except last n elements.
e

Egor Okhterov

01/21/2020, 10:24 AM
array.dropLast(n)
f

frogger

01/21/2020, 10:24 AM
n
as in any index, not necessesarily the last one
e

Egor Okhterov

01/21/2020, 10:24 AM
n is the number of elements
s

Shawn

01/21/2020, 10:24 AM
This isn’t a great operation for a Kotlin array - elements aren’t linked so repeated scanning will have to occur to get your result
you can do this:
inline fun <reified T> Array<T>.withoutIndex(index: Int): Array<T> =
    (dropLast(index + 1) + drop(index + 1)).toTypedArray()
but if you need to arbitrarily drop elements within this collection a lot, consider a LinkedList instead?
f

frogger

01/21/2020, 10:25 AM
n is the number of elements
bold claim
😂 3
e

Egor Okhterov

01/21/2020, 10:25 AM
Oh, you mean without
n'th
element
👍 2
Usually people use the other variable for that, so I was confused 😃
f

frogger

01/21/2020, 10:26 AM
No worries, I noticed my question wasn't crystal clear
d

diesieben07

01/21/2020, 10:29 AM
An optimized version: https://pl.kotl.in/90_QAXN2D
👏 1
s

Shawn

01/21/2020, 10:30 AM
this might be a hair better?
inline fun <reified T> Array<T>.withoutIndex(index: Int): Array<T> =
    sliceArray(0 until index) + sliceArray((index + 1) until size)
d

diesieben07

01/21/2020, 10:30 AM
That's 3 array copy operations
s

Shawn

01/21/2020, 10:30 AM
sorry, didn’t mean relative to your suggestion @diesieben07
just iterating on my last suggestion
d

diesieben07

01/21/2020, 10:30 AM
And it's allocating 3 new arrays
f

frogger

01/21/2020, 10:32 AM
Thanks @diesieben07 and @Shawn super helpful, I'll try your suggestions. 📗
👍 1
e

Egor Okhterov

01/21/2020, 10:33 AM
arr.filterIndexed { i, _ -> i != n }
👍 2
2
t

tseisel

01/21/2020, 10:40 AM
If you are using arrays instead of lists for performance reasons, you should stick with
System.arraycopy
(JVM-only).
d

diesieben07

01/21/2020, 10:40 AM
(Which is what
copyInto
uses)
👍 1