Filter accepts a function that returns a boolean. The function is ran over the array elements. If the function returns true, the element passes the filter and is added to the new array of filtered elements. If false, the element is skipped (or in other words filtered out). After iterating through al
(fn func(index int, value *Value) bool)
| 440 | // }) |
| 441 | // filteredArray.IsEqual([]interface{}{"foo"}) //succeeds |
| 442 | func (a *Array) Filter(fn func(index int, value *Value) bool) *Array { |
| 443 | opChain := a.chain.enter("Filter()") |
| 444 | defer opChain.leave() |
| 445 | |
| 446 | if opChain.failed() { |
| 447 | return newArray(opChain, nil) |
| 448 | } |
| 449 | |
| 450 | if fn == nil { |
| 451 | opChain.fail(AssertionFailure{ |
| 452 | Type: AssertUsage, |
| 453 | Errors: []error{ |
| 454 | errors.New("unexpected nil function argument"), |
| 455 | }, |
| 456 | }) |
| 457 | return newArray(opChain, nil) |
| 458 | } |
| 459 | |
| 460 | filteredArray := []interface{}{} |
| 461 | |
| 462 | for index, element := range a.value { |
| 463 | func() { |
| 464 | valueChain := opChain.replace("Filter[%d]", index) |
| 465 | defer valueChain.leave() |
| 466 | |
| 467 | valueChain.setRoot() |
| 468 | valueChain.setSeverity(SeverityLog) |
| 469 | |
| 470 | if fn(index, newValue(valueChain, element)) && !valueChain.treeFailed() { |
| 471 | filteredArray = append(filteredArray, element) |
| 472 | } |
| 473 | }() |
| 474 | } |
| 475 | |
| 476 | return newArray(opChain, filteredArray) |
| 477 | } |
| 478 | |
| 479 | // Transform runs the passed function on all the elements in the array |
| 480 | // and returns a new array without effeecting original array. |