gpt4 book ai didi

javascript - 如何将数组中的数据过滤到另一个数组中?

转载 作者:行者123 更新时间:2023-12-01 00:26:58 27 4
gpt4 key购买 nike

我正在 React 中构建一个纸牌游戏应用程序,并尝试过滤当前数组中包含多个“纸牌”的数组的值是否为 6。例如:

let arr = [{type: "span", key: "51", ref: null, props: {children: "6"}}, { type: "span", key: "52", ref: null, props: {children: "7"}}, { type: "span", key: "53", ref: null, props: {children: "6"}}]
let arr2 = [{ type: "span", key: "50", ref: null, props: {children: "6"}}]

let result = arr.filter((card) => {
return arr2 === card
})
console.log(result) //returns []
//I want it to return the items that have props:{children: "6"}

然后我需要从 arr 中删除该项目并将其放入 arr2 中。那我会做这样的事情吗?

this.setState(({arr2, arr}) => {
return {
arr2: [...arr2, ...arr.slice(0, 1)],
arr: [...arr.slice(1, arr.length)]

};
});

最佳答案

您可以在filter中使用some来根据props值获取公共(public)元素。

let arr = [{
type: "span",
key: "51",
ref: null,
props: {
children: "6"
}
}, {
type: "span",
key: "52",
ref: null,
props: {
children: "7"
}
}, {
type: "span",
key: "53",
ref: null,
props: {
children: "6"
}
}]

let arr2 = [{
type: "span",
key: "50",
ref: null,
props: {
children: "6"
}
}]

let result = arr.filter((card, index) => {
return arr2.some(function(card2){
return card2.props.children === card.props.children
});
})

arr = arr.filter((card, index) => {
return arr2.some(function(card2){
return card2.props.children !== card.props.children
});
})
arr2 = arr2.concat(result)
console.log("arr list are:")
console.log(arr)
console.log("arr2 list are:")
console.log(arr2)

希望有帮助:)

关于javascript - 如何将数组中的数据过滤到另一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895502/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com