我有一个固定的数组:
x = [
{value: 0, text: "hello world"},
{value: 1, text: "how are you?"},
{value: 2, text: "no problem"}
{value: 3, text: "anything else?"}
{value: 4, text: "other dummy text"}
]另一个动态数组:
y = [2, 4]我想根据数组"y“的值过滤数组"x”。
预期结果应是:
x = [
{value: 2, text: "no problem"},
{value: 4, text: "other dummy text"}
]我怎么能这么做?
谢谢
发布于 2022-05-04 08:24:41
在获得动态数组值之后。您可以像这样运行代码,它为动态数组值过滤数组。
let x = [
{value: 0, text: "hello world"},
{value: 1, text: "how are you?"},
{value: 2, text: "no problem"},
{value: 3, text: "anything else?"},
{value: 4, text: "other dummy text"}
];
const y=[2,4];
x = x.filter( data => (y.includes(data.value)));
console.log(x);
发布于 2022-05-04 08:25:26
您要寻找的是筛选数组x,并检查其值是否包含在数组y中。
const x = [
{ value: 0, text: "hello world" },
{ value: 1, text: "how are you?" },
{ value: 2, text: "no problem" },
{ value: 3, text: "anything else?" },
{ value: 4, text: "other dummy text" }
];
const y = [2, 4];
const result = x.filter((item) => y.includes(item.value));
console.log(result);发布于 2022-05-04 08:25:16
这就对了。
x = [
{value: 0, text: "hello world"},
{value: 1, text: "how are you?"},
{value: 2, text: "no problem"},
{value: 3, text: "anything else?"},
{value: 4, text: "other dummy text"}
]
y = [2, 4]
z = []
for (var i = 0;i<x.length;i++){
for (var j = 0;j<y.length;j++){
if (x[i].value == y[j]){z.push(x[i])}
}
}
console.log(z)
https://stackoverflow.com/questions/72109828
复制相似问题