-2

I have an array of maps, from which I want to delete an element if it exists, which is determined by its "key".

How to do it? I want it not to be slow. Preserving the order isn't important.

myMaps = []map[string]interface{} {
  map[string]interface{} {"key": "aaa", "key2": 222, "key3": "aafdsafd"},
  map[string]interface{} {"key": "key_to_delete", "key2": 366, "key3": "333aafdsafd"},
  map[string]interface{} {"key": "cccc", "key2": 467, "key3": "jhgfjhg"}, 
}
for _, x := range myMaps {
  if x["key"] == "key_to_delete" {
    //delete this element as a) key of the map b) the map-element as an element of the array; How?
  }
}

The delete(...) function:

when iterating over an array, a copy of it is what gets passed in the body of a loop. No? How would then delete(...) delete an element from the real array?

update:

I need to know of how to delete 2 types of entities, and for my case:

  • an element of an array - a map
  • an element of a map, with a certain key

Without using a third-party library.

Koharim67
  • 9
  • 2

1 Answers1

0

If you want to delete the key from the map:

for _, x := range myMaps {
    if x["key"] == "key_to_delete" {
        delete(x, "key")
    }
}

If what you want is to delete the map from the array it gets complicated, you're better off creating a second array and inserting into it if the current map is to be kept:

myFilteredMaps := make([]map[string]interface{}, 0, len(myMaps))
for _, x := range myMaps {
    if x["key"] != "key_to_delete" {
        myFilteredMaps = append(myFilteredMaps, x)
    }
}
myMaps = myFilteredMaps

Both of these are pretty quick so long as len(myMaps) isn't too large, both have linear runtime with respect to that length.

Ezequiel Muns
  • 7,492
  • 33
  • 57
  • wouldn't the 2nd solution be slow? it'd involve creating a new array of maps, that is; is there a way to optimize it? – Koharim67 Oct 26 '21 at 12:18
  • Slowness is relative: if you're dealing with up to a couple of hundred maps, it's unlikely to be a problem (but that depends on how performance sensitive the program you're writing is). In any care, the constraint of it being an __array__ of maps prevent a faster solution that is less than linear in the array length. – Ezequiel Muns Oct 26 '21 at 12:23
  • If you need to delete an item from an array, all the subsequent items need to be moved one spot, which is a linear operation. so yes a version that does not create a new array will be quicker, but not a whole lot (compared to for example, having a map of maps which come with a constant amortized time cost for item deletion). – Ezequiel Muns Oct 26 '21 at 12:29