【问题标题】:Create new array with deleted values (React Native)创建具有已删除值的新数组(React Native)
【发布时间】:2018-09-04 10:45:11
【问题描述】:

我有一个这样的数组:

[
Object {
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
Object {
"hex": "#50690e",
"label": "text",
"value": "354",
},
Object {
"hex": "#925fa3",
"label": "text",
"value": "355"
}]

我有另一个数组:

Array [
"355",
"356"
]

我希望创建第一个数组,但没有包含值 355 和 356 的对象。我尝试使用 .filter()... 但我是 JS 和 React Native 的新手 :-)

我尝试了一些东西,但几乎每次我只用值重新创建我的数组(我丢失了里面的对象)......

我想做的是: 如果我在我的第一个数组中找到 355 和 356,我会删除它们的对象,然后我用剩下的唯一对象(值 364)重新创建我的数组

我在想这样的事情: myFirstArray.filter(item => item.value != mySecondArray.value) 但这并不成功......

感谢您的帮助

【问题讨论】:

标签: javascript arrays object react-native


【解决方案1】:

前面的答案涉及多次迭代您的 id 数组。

更高效的解决方案是将 id 存储在一个集合中,然后将其与过滤器结合使用来生成新数组。

const arr = [
     {
    "hex": "#00b2b9",
    "label": "text",
    "value": "364",
    },
     ...,
     {
    "hex": "#925fa3",
    "label": "text",
    "value": "355"
    }];

const ids = ["354", "355"];

const idSet = new Set(ids);
const output = arr.filter(e => !idSet.has(e.value));

【讨论】:

    【解决方案2】:
    var firstArray = [{
    "hex": "#00b2b9",
    "label": "text",
    "value": "364",
    },
    {
    "hex": "#50690e",
    "label": "text",
    "value": "354",
    },
    {
    "hex": "#925fa3",
    "label": "text",
    "value": "355"
    }]
    
    var secondArray = [
    "355",
    "356"
    ]
    
    var thirdArray = firstArray.filter(item => secondArray.includes(item.value))
    
    console.log(thirdArray)
    

    【讨论】:

    • 谢谢拉扎尔!它正在工作。你们都带着同样的想法。太酷了
    【解决方案3】:

    你快到了,只需使用Array#includes() 来确定一个项目的值是否在第二个数组中:

    myFirstArray.filter(item => !mySecondArray.includes(item.value))
    

    let myFirstArray = [{
        "hex": "#00b2b9",
        "label": "text",
        "value": "364",
      },
      {
        "hex": "#50690e",
        "label": "text",
        "value": "354",
      },
      {
        "hex": "#925fa3",
        "label": "text",
        "value": "355"
      }
    ]
    
    let mySecondArray = [
      "355",
      "356"
    ]
    
    console.log(
      myFirstArray.filter(item => !mySecondArray.includes(item.value))
    )

    【讨论】:

    • 谢谢卢卡!它的工作。我是如此接近,但现在最好理解这个概念!
    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 2018-09-29
    • 1970-01-01
    • 2022-07-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多