Reputation: 77
I'm new to Powershell and trying to get a few functions together. I've created a function that creates an array from input. I'm also trying to create a function that add elements at a specified index without using lists (I know that lists are so much easier, but I'm trying to understand how to do it without lists).
This is my code so far. I just can't get this to work, I've tried with loops and the code below, any help is appreciated.
Kind Regards!
Function Create_array ($index, $value)
{
$array = new-object array[] $index
if ($value)
{
for ($i = 0;$i -lt $array.length;$i++)
{
$array[$i] = $value
}
write-host ""
write-host "Grattis!! Din array är nu skapad med angivet index och värde."
}
else
{
for ($i = 0;$i -lt $array.length;$i++)
{
$array[$i] = "Hej $env:username och välkommen till Dennis och Jonas script. Detta är en defaulttext, ange ett eget index följt av önskat värde"
}
write-host ""
write-host "Array är nu skapad med defaultvärden"
}
return $array
}
Function Add_to_array ($nyarray, $value, $index) # Lägger till ett värde på angivet index eller längst ner om index ej anges.
{
if ($index -gt $nyarray.length)
{
$i = $nyarray.length
write-host "Du har angivit ett felaktigt index. Din array innehåller $i element"
}
elseif ($index -gt 2) # Kollar om det angivna indexet är större än 2
{
$nyarray[$index - 2] += $värde # Om större än 2: Angivna värdet läggs in på angivet index ($index - 2)
write-host "Element är nu inlagt på angivet index i din array"
} # och resten flyttas ner.
elseif ($index -eq 1) # Kollar om angivet index är mindre än 2
{
$nyarray[0] += $värde # Om mindre sätts det angivna värdet in på index 1 (0)
write-host "Element är nu inlagt på angivet index i din array"
}
else
{
$nyarray += $värde # Om inget index anges sätter denna funktion in det angivna värdet längst ner.
write-host "Element är nu inlagt längst ner i din array"
}
return $nyarray # Lägger in den "nya" arrayen i det variabelnamn man valt.
}
Upvotes: 6
Views: 16590
Reputation: 971
Function InsertToArray($Array, $insertIndex, $valueToInsert){
return @(
for ($i = 0; $i -lt $insertIndex; $i++) {
$Array[$i]
}
$valueToInsert
for ($i = $insertIndex; $i -lt $Array.Length; $i++) {
$Array[$i]
}
)
}
Upvotes: 0
Reputation: 68273
You can do it with array slicing:
$array = @(1,2,4,5)
$value = 3
$index = 2
$array = $array[0..($index -1)] + $value + $array[$index..($array.Length -1)]
$array
Upvotes: 1
Reputation: 116
If we need flat array in result, we can use sum operator:
Code bellow is adding [string]'Word'
at position 4 of $array1
$new_array = @($array1[0..3]) + @('Word') + @($array1[4..5])
use-case is concatenate two flat arrays together, or add some data at some position of fixed array.
Upvotes: 6
Reputation: 31
This is how i managed it. Wrapped into a function. Although you may have issues. if your array values are very long.
$myArray = @("how","to","slice","into","an","array")
Function Insert-ToArray($Array, $insertAfter, $valueToInsert){
#find the index of value before insertion
$insertPoint = $Array.IndexOf($insertAfter)
#split the array into two parts
$firstHalf = $Array[0..$insertPoint]
$secondHalf = $Array[($insertPoint +1)..$Array.Length]
#slice into a new array
$newArray = @($firstHalf,$valueToInsert,$secondHalf)
return $newArray
#returning this new array means you can assign it over the old array
}
$myArray = Insert-ToArray -Array $myArray -insertAfter "slice" -valueToInsert "something"
$myArray
Upvotes: 3
Reputation: 24071
As you claim you are trying to understand how to work without List, I'll explain how arrays work behind the scenes. This kind of data manipulation is mostly encountered on low-level programming, like data structures classes and C programming. High-level languages like Java, C# and Powershell do employ these techniques, but actual implementations are way hidden from the user. Still, the runtime does something akin these steps.
Array as a basic data structure do not actually support insert. Array supports only read and write operations. Think an array as a squared maths paper, in which each array cell is a square on the paper. Write some text into the paper (pipe chars illustriate the squares and numbers are indexes):
0 1 2 3 4 5 6 7
|t|s|t| |t|e|x|t|
Now consider inserting missing e
letter into the word tst
to make it test
. What'll happen? A new array is needed:
0 1 2 3 4 5 6 7 8
|t|e|s|t| |t|e|x|t|
Note that after inserting e
into 2nd cell, all the remaining letters are moved one step forward. So what happened? The insertion routine you did by hand was like so,
As you can see, the process is a bit cubersome. When "inserting" a letter on the paper, you don't create new, empty cell in the original array. You have to copy all the elements by hand.
As an alternative for a brand new array, you can resize the array by adding an extra cell into it. Then, instead of copying letters to new array, you'd start from the end of the array and copy letters one step forward until at the insertion index. Then you add the inserted letter and stop. So,
0 1 2 3 4 5 6 7 8
|t|s|t| |t|e|x|t| | # start
|t|s|t| |t|e|x|t|t| # moved last t to the end
|t|s|t| |t|e|x|x|t| # overwrite old t with x
|t|s|t| |t|e|e|x|t| # overwrite old x with e
|t|s|t| |t|t|e|x|t| # and so on
|t|s|t| | |t|e|x|t|
|t|s|t|t| |t|e|x|t|
|t|s|s|t| |t|e|x|t| # insert location reached after this
|t|e|s|t| |t|e|x|t| # don't overwrite s with t but e. Done!
Now that you understand how array insertion works, mjolinor's example is easy to understand. A new array is created by copying elements from start to insertion point, adding the insert and copying the rest of the array contents.
Upvotes: 1