【问题标题】:How to filter out array data based on some outer conditions in react.jsreact.js中如何根据一些外部条件过滤掉数组数据
【发布时间】:2021-07-22 18:42:59
【问题描述】:
const arr=['A','B'];
arr.filter(()=>{
if(type==all){return full array}
else{return arr[1]}
)

我想要的是,只要类型全部返回完整数组,但对于其余条件,只返回索引 1 处的元素。

【问题讨论】:

标签: javascript arrays reactjs filter


【解决方案1】:

您可以使用条件运算符直接返回数组

试试:-

const arr=['A','B'];
return type === all ? arr : arr[1]

或者您可以使用如下过滤器:-

const arr=['A','B'];
const filteredArray = arr.filter((value, index) => type === all || index === 1);

【讨论】:

  • 你能帮我在这里如何使用过滤功能
【解决方案2】:

只在type不是all时过滤,否则返回原始数据:

演示:

const arr = [{type: "A", value: "A"}, {type: "B", value: "B"}]
let type = ""

const filterArr = () => {
  if (type === "all") {
    return arr // Don't filter
  }
  return arr.filter(item => item.type === type) // Filter when type is other than "all"
}

type = "all"
console.log(filterArr())

type = "B"
console.log(filterArr())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 2021-01-03
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2019-06-30
    • 1970-01-01
    相关资源
    最近更新 更多