【问题标题】:filter out array with array javascript [duplicate]用数组javascript过滤掉数组[重复]
【发布时间】:2021-07-21 18:41:04
【问题描述】:

如何过滤出对象数组 a,其中 item1 是数组 b 的一部分?

a = [
{
    "item1": "apple",
    "item2": "banana"
},
{
    "item1": "apple",
    "item2": "cherry"
},
{
    "item1": "melon",
    "item2": "cherry"
},
{
    "item1": "banana",
    "item2": "melon"
}]



b = [ "apple", "banana"]

预期的数组是:

expected_array = [{
                     "item": "melon",
                     "item2": "cherry"
                  }]

我试过了:

a.filter(el => !b.includes(el.item1))

但结果数组的长度与原始数组相同。

我在 Node Red 中执行此操作,这是我的测试设置:

[{"id":"ab67374c.c64458","type":"debug","z":"42edc0b9.7ba91","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":2040,"y":300,"wires":[]},{"id":"3fbdbc18.951c94","type":"function","z":"42edc0b9.7ba91","name":"cycle counter","func":"\n\nmsg.payload = msg.payload.filter(el => !msg.exclude.includes(el.altname));\n\nnode.warn(msg.payload);\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1810,"y":320,"wires":[["ab67374c.c64458"]]},{"id":"b4b2e91f.8e4368","type":"inject","z":"42edc0b9.7ba91","name":"","props":[{"p":"payload"},{"p":"exclude","v":"[[\"melon\"],[\"banana\"]]","vt":"json"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"altname\":\"melon\"},{\"altname\":\"cherry\"},{\"altname\":\"banana\"}]","payloadType":"json","x":1650,"y":320,"wires":[["3fbdbc18.951c94"]]}]

【问题讨论】:

  • 不,输出只有一个元素。您的代码正在运行。
  • 您是否保存了a.filter 调用的结果? filter 不会改变数组。展示一个完整示例,说明如何使用和测试 a.filter(...) 调用的结果。
  • 您可能希望 filter 变为 mutate a。不,它返回一个新数组。你应该检查它的返回值。如果您愿意,可以将该返回值重新分配给 a
  • 感谢您的解释。我在节点红色中执行此操作,我似乎无法过滤掉数组。有人可以看看我的设置吗?我已将我的 Node Red 设置添加到问题中

标签: javascript arrays filter node-red


【解决方案1】:

正如其他人在 cmets 中所说,您的代码很好,但您需要将过滤器函数的输出分配给变量。

let a = [{
    "item1": "apple",
    "item2": "banana"
  },
  {
    "item1": "apple",
    "item2": "cherry"
  },
  {
    "item1": "melon",
    "item2": "cherry"
  },
  {
    "item1": "banana",
    "item2": "melon"
  }
];
let b = ["apple", "banana"];

// assign filter output to variable `c`
let c = a.filter(el => !b.includes(el.item1));

console.log(c); // your output

【讨论】:

  • 感谢您的解释。我在节点红色中执行此操作,但我似乎无法过滤掉数组。有人可以看看我的设置吗?我已将我的 Node Red 设置添加到问题中
猜你喜欢
  • 1970-01-01
  • 2018-03-21
  • 2020-02-24
  • 2017-07-19
  • 1970-01-01
  • 2022-11-17
  • 2017-03-25
  • 2018-01-18
  • 2021-10-21
相关资源
最近更新 更多