从动态数组中筛选对象数组



我有一个固定的数组:

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]

我想过滤数组"x"基于数组"y">

中的值预期结果应该是:

x = [
{value: 2, text: "no problem"},
{value: 4, text: "other dummy text"}
]

我怎么能这么做?

感谢

获取动态数组值后。您可以像这样运行代码它过滤数组中的动态数组值

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);

您要查找的是筛选数组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);

好了。

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)

另一种使用.reduce的方式:

const data = [
{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"}
];
function selectValuesFrom(xs, ys) {
return ys.reduce( // fold ys into a new array
(a, y) => {
// try to find an "x" by the given "y" value
const r = xs.find(x => x.value === y);
// if there is an "x", add it to the new array, otherwise
// skip it
return r ? a.concat(r) : a;
},
[]
);
}
console.log(selectValuesFrom(data, [2, 4]));
console.log(selectValuesFrom(data, [3, 1, 5]));

最新更新