0

I want to filter the second array, cards, so that it only shows records specified in the cardsfFilter array which is in the first object ( id=1) in the groups.cardsFilter array

ARRAYS AND REQUIRED RESULT ARE BELOW

const groups = [
  {
    id: 1,
    name: 'Melbourne Bands',
//Below is the array that I need to act as the filter for the cards array
    cardsFilter: [1, 2]
  },
  {
    id: 2,
    name: 'Sydney Bands',
    cardsFilter: [3]
  }
]

const cards =  [
  {
    id: '1',
    url: 'jimmyyukka.com',
    name: 'Jimmy Yukka',
    CreatedByUserId: 1
  },
  {
    id: '2',
    url: 'jimmyyukka.com',
    name: 'Due North',
    CreatedByUserId: 1
  },
  {
    id: '3',
    url: 'jimmyyukka.com',
    name: 'INXS',
    CreatedByUserId: 1
  }
]


const desiredResult = [
  {
    id: '1',
    url: 'jimmyyukka.com',
    name: 'Jimmy Yukka',
    CreatedByUserId: 1
  },
  {
    id: '2',
    url: 'jimmyyukka.com',
    name: 'Due North',
    CreatedByUserId: 1
  },
]

I am struggling to figure it out and can't find an example on stack overflow for this simple approach.

I HAVE TRIED (one record) I can't figure out how to do this with the array

const notQuiteRight= cards.filter(function(getFile){
  return getFile.id === "1"
});
2
  • So you only want to use the array in the first object as the filter? Commented Dec 13, 2019 at 2:46
  • yes so I need in effect to filter the cards array with the array cardsFilter: [1, 2] Commented Dec 13, 2019 at 2:52

1 Answer 1

3

Extract the property cardsFilter from first object of groups array and then use filter on cards array.

const groups = [{
    id: 1,
    name: 'Melbourne Bands',
    //Below is the array that I need to act as the filter for the cards array
    cardsFilter: [1, 2]
  },
  {
    id: 2,
    name: 'Sydney Bands',
    cardsFilter: [3]
  }
]

const cards = [{
    id: '1',
    url: 'jimmyyukka.com',
    name: 'Jimmy Yukka',
    CreatedByUserId: 1
  },
  {
    id: '2',
    url: 'jimmyyukka.com',
    name: 'Due North',
    CreatedByUserId: 1
  },
  {
    id: '3',
    url: 'jimmyyukka.com',
    name: 'INXS',
    CreatedByUserId: 1
  }
]


const { cardsFilter } = groups[0];

const desiredOutput = cards.filter(({id}) => cardsFilter.includes(+id));

console.log(desiredOutput);

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

1 Comment

Thanks so much! A simple , elegant solution but I was faffing about for ages trying to figure it out

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.