Junior — Middle
How to extract elements from the original array that are missing in the data as a slice?
sobes.tech AI
Answer from AI
To extract elements from the original array that are not in another slice, you can use a map for quick lookup and filtering. For example, if you have an original array and a slice with elements to exclude, create a map from the slice elements, then iterate over the original array and add to the result only those elements that are not in the map.
Example in Go:
package main
import "fmt"
func difference(arr []int, exclude []int) []int {
excludeMap := make(map[int]bool)
for _, v := range exclude {
excludeMap[v] = true
}
var result []int
for _, v := range arr {
if !excludeMap[v] {
result = append(result, v)
}
}
return result
}
func main() {
arr := []int{1, 2, 3, 4, 5}
exclude := []int{2, 4}
fmt.Println(difference(arr, exclude)) // Output: [1 3 5]
}
This approach is efficient and simple to implement.