3bag
3bag

Reputation: 25

How to filter data in array to another array?

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

        };
      });

Upvotes: 0

Views: 60

Answers (2)

Arun AK
Arun AK

Reputation: 4370

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

Upvotes: 2

zimmerbimmer
zimmerbimmer

Reputation: 948

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

Upvotes: 0

Related Questions