【问题标题】:ES6: How to compare values in two arrays [duplicate]ES6:如何比较两个数组中的值
【发布时间】:2018-07-23 13:07:59
【问题描述】:

我有两个数组;

let items = {
    search: [
       ['car', 'door', 'pen']
    ]
}

let data.props = [];

data.props = [
    {label: "car"}, 
    {label: "window"},
    {label: "kettle"},
    {label: "chair"},
    {label: "door"},
]

如何使用 es6 检查/比较两个数组?对我来说有点棘手,因为items[] 是一个嵌套数组。

我只检查第一项。

if (data.props['0'].label === items.search['0'].values['0']) {
        let searchItems = [];
        searchItems.push(data.props['0']);
        console.log(searchItems);
    }

【问题讨论】:

  • “检查/比较两个数组”是什么意思?请提供所需的输出并展示您实现该要求的尝试。
  • 你的目标是什么?
  • 请访问help center,使用tour查看内容和How to Ask。做一些研究,搜索关于 SO 的相关主题;如果您遇到困难,请发布您的尝试minimal reproducible example,并注明输入和预期输出。
  • 你的代码是无效的JS。你不能在没有对象的情况下分配给 data.props 并且你不应该引用数组 indicii
  • 您的代码在您编辑后不再有效。请阅读数组与对象。 search: [ values: ['car', 'door', 'pen'] ] 不是有效的数组条目。使用<> 创建一个 sn-p 并对其进行测试以创建一个 minimal reproducible example

标签: javascript ecmascript-6


【解决方案1】:
let items = {
    search: {
        values: ['car', 'door', 'pen']
    }
}

let data = {
  props: [
        {label: "window"}, 
        {label: "car"},
        {label: "kettle"},
        {label: "chair"},
        {label: "door"},
    ]
}

console.log(data.props.filter(prop => items.search.values.indexOf(prop.label) >= 0));

日志输出为:

[0]: {label: "car"}
[1]: {label: "door"}

【讨论】:

  • 为什么要过滤两次:data.props.filter(prop => items.search.values.indexOf(prop.label) >= 0)
【解决方案2】:

您可以使用流:

// if multiple search values:
const items = {
    search: {
        values: ['car', 'door', 'pen']
    }
}

let data = {
  props: []
};

data.props = [
    {label: "window"}, 
    {label: "car"},
    {label: "kettle"},
    {label: "chair"},
    {label: "door"},
];

let matches = data.props
  .map(prop => prop.label)
  .filter(prop => items.search.values.indexOf(prop) >= 0);
  
console.log(matches);

// if one search value

let searchItem = "car";

matches = data.props
  .map(prop => prop.label)
  .filter(prop => searchItem === prop);
  
console.log(matches);

【讨论】:

  • 搜索是一个有一个值的数组。有人错误地编辑了我的问题
  • 只要它是一个数组,它应该仍然可以工作。
  • 我也为一项添加了答案 :)
  • 有趣.. 我在indexOf 下得到一条红线。记住search[] 而不是{}.. 打字稿错误。但这应该为我指明正确的方向,谢谢。
  • 搜索不应该是 [],除非它是 search: ['car', 'door', 'pen']
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多