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

时间:2019-11-16 21:48:07

标签: 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 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)]

        };
      });

2 个答案:

答案 0 :(得分:2)

您可以在some内使用filter来获取基于props值的公共元素。

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)

希望它会有所帮助:)

答案 1 :(得分:0)

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