Skip to main content
Deno 2 is finally here ๐ŸŽ‰๏ธ
Learn more
Module

x/denops_std/function/mod.ts>filter

๐Ÿ“š Standard module for denops.vim
Go to Latest
function filter
import { filter } from "https://deno.land/x/denops_std@v5.0.2/function/mod.ts";

{expr1} must be a List, String, Blob or Dictionary. For each item in {expr1} evaluate {expr2} and when the result is zero or false remove the item from the List or Dictionary. Similarly for each byte in a Blob and each character in a String.

{expr2} must be a string or Funcref.

If {expr2} is a string, inside {expr2} v:val has the value of the current item. For a Dictionary v:key has the key of the current item and for a List v:key has the index of the current item. For a Blob v:key has the index of the current byte. For a String v:key has the index of the current character. Examples:

call filter(mylist, 'v:val !~ "OLD"')

Removes the items where "OLD" appears.

call filter(mydict, 'v:key >= 8')

Removes the items with a key below 8.

call filter(var, 0)

Removes all the items, thus clears the List or Dictionary.

Note that {expr2} is the result of expression and is then used as an expression again. Often it is good to use a literal-string to avoid having to double backslashes.

If {expr2} is a Funcref it must take two arguments: 1. the key or the index of the current item. 2. the value of the current item. The function must return TRUE if the item should be kept. Example that keeps the odd items of a list:

func Odd(idx, val)
  return a:idx % 2 == 1
endfunc
call filter(mylist, function('Odd'))

It is shorter when using a lambda. In Vim9 syntax:

call filter(myList, (idx, val) => idx * val <= 42)

In legacy script syntax:

call filter(myList, {idx, val -> idx * val <= 42})

If you do not use "val" you can leave it out:

call filter(myList, {idx -> idx % 2 == 1})

In Vim9 script the result must be true, false, zero or one. Other values will result in a type error.

For a List and a Dictionary the operation is done in-place. If you want it to remain unmodified make a copy first:

:let l = filter(copy(mylist), 'v:val =~ "KEEP"')

Returns {expr1}, the List or Dictionary that was filtered, or a new Blob or String. When an error is encountered while evaluating {expr2} no further items in {expr1} are processed. When {expr2} is a Funcref errors inside a function are ignored, unless it was defined with the "abort" flag.

Can also be used as a method:

mylist->filter(expr2)

Parameters

denops: Denops
expr1: unknown
expr2: unknown

Returns

Promise<
| unknown[]
| Record<string, unknown>
| unknown
| string
>