0

I am building a card game app in React and am trying to filter if one array that has multiple 'cards' has a value of 6 in the present array. For example:

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"}

And then I need to remove the item from arr and place it in arr2. Then i would do something like this?

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

        };
      });
1
  • arr2 === card will never be true. Two Array instances are always distinct. Commented Nov 16, 2019 at 22:07

2 Answers 2

2

You can use some inside the filter to get the common elements based on the props value.

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)

Hope it helps :)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.