Home > Software design >  How to get the last element iterating over slice
How to get the last element iterating over slice

Time:10-17

The task is to remove duplicated elements in slice. I tried the next to do it:

package main

import "fmt"

func main() {
    arr := []string{"1", "2", "2", "3", "2", "3"}
    var newArr []string
    for i := range arr[:len(arr)-1] {
        if arr[i] != arr[i 1] {
            newArr = append(newArr, arr[i])
        }
    }
    fmt.Println(newArr)
}

The output here is [1 2 3 2] but I expect [1 2 3 2 3]. How to iterate properly and get the last element too?

CodePudding user response:

With this algorithm, you never check the last element. The loop ends at the element before the last. Either check the last element later, or change the algorithm to check the previous element:

for i := range arr {
   if i==0  || arr[i]!=arr[i-1] {
     newArr=append(newArr,arr[i])
   }
}
 
  • Related