【问题标题】:can't filter an empty array inside another array (typescript)无法过滤另一个数组中的空数组(打字稿)
【发布时间】:2021-04-23 04:27:21
【问题描述】:

这是我第一次来这里,所以如果我忘记提及某些事情,请不要生气:)

我正在处理 Typescript 任务,需要一些帮助。 我有这个价值: let values = [["id-1", "id_2"], true, true](长度为3)。

带有 id 的第一个数组是一个多选下拉列表,所以当我取消选择它们时,我有这个 values = [[], true, true] (长度仍然是 3)。

我想将此数组过滤为长度为 2(在本例中),然后将空数组从数组中推出。

数组的类型是“boolean | string[]”,我试过检查长度,我试过indexOf......但它不起作用。 有什么想法吗?

谢谢:)

【问题讨论】:

    标签: arrays typescript


    【解决方案1】:

    您是否打算过滤数组的所有“空”值,包括 false boolean 值?还是只是删除空数组?

    此逻辑仅删除空数组。 .filter() 回调在应保留项目时返回 true。所以我们说如果valuearray,那么只有当长度大于0 时才返回true。但如果它不是array,那么总是返回true

    type MyArrayType = (boolean | string[])[];
    
    const filterMyArray = (array: MyArrayType): MyArrayType => {
        return array.filter(value => Array.isArray(value) ? value.length > 0 : true )
    }
    
    const a =  [["id-1", "id_2"], true, true]
    const b = [[], true, true]
    const c = [[], false, true]
    
    console.log(filterMyArray(a)); // -> [["id-1", "id_2"], true, true] 
    console.log(filterMyArray(b)); // -> [true, true] 
    console.log(filterMyArray(c)); // -> [false, true] 
    

    Typescript Playground Link

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 2022-01-22
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 2019-02-13
      • 2017-08-10
      • 1970-01-01
      相关资源
      最近更新 更多