Javascript 如何将数组中的数据筛选到另一个数组?
我正在React中构建一个纸牌游戏应用程序,并尝试筛选当前阵列中是否有一个包含多张“牌”的阵列的值为6。例如:Javascript 如何将数组中的数据筛选到另一个数组?,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我正在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 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)]
};
});
您可以在
过滤器中使用some
,根据props值获取公共元素
让arr=[{
键入:“span”,
钥匙:“51”,
ref:null,
道具:{
儿童:“6”
}
}, {
键入:“span”,
钥匙:“52”,
ref:null,
道具:{
儿童:“7”
}
}, {
键入:“span”,
钥匙:“53”,
ref:null,
道具:{
儿童:“6”
}
}]
设arr2=[{
键入:“span”,
钥匙:“50”,
ref:null,
道具:{
儿童:“6”
}
}]
let result=arr.filter((卡片、索引)=>{
返回arr2.some(函数(card2){
返回card2.props.children===card.props.children
});
})
arr=arr.filter((卡片,索引)=>{
返回arr2.some(函数(card2){
返回card2.props.children!==card.props.children
});
})
arr2=arr2.concat(结果)
日志(“arr列表为:”)
控制台日志(arr)
log(“arr2列表为:”)
console.log(arr2)
您可以使用过滤器中的部分
,根据props值获取公共元素
让arr=[{
键入:“span”,
钥匙:“51”,
ref:null,
道具:{
儿童:“6”
}
}, {
键入:“span”,
钥匙:“52”,
ref:null,
道具:{
儿童:“7”
}
}, {
键入:“span”,
钥匙:“53”,
ref:null,
道具:{
儿童:“6”
}
}]
设arr2=[{
键入:“span”,
钥匙:“50”,
ref:null,
道具:{
儿童:“6”
}
}]
let result=arr.filter((卡片、索引)=>{
返回arr2.some(函数(card2){
返回card2.props.children===card.props.children
});
})
arr=arr.filter((卡片,索引)=>{
返回arr2.some(函数(card2){
返回card2.props.children!==card.props.children
});
})
arr2=arr2.concat(结果)
日志(“arr列表为:”)
控制台日志(arr)
log(“arr2列表为:”)
console.log(arr2)
arr2===card
将永远不会为真。两个Array
实例总是不同的。arr2===card
永远不会为真。两个Array
实例总是不同的。
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 => card.props.children === '6'
? arr2.push(card)
: null
); //If children: 6 then add it to arr2
arr = arr.filter(card => card.props.children !== '6'); //Remove from arr the ones that has children: 6
console.log(result);
console.log(arr2);
console.log(arr);