2

I have two arrays: First - jobs array of objects that contains array itemIds, like this:

jobs: [{
        name: null
        id: 612
        items: []
        stat: 1
        itemIds: [223, 1234]
    },
    {
        name: null
        id: 734
        items: []
        stat: 2
        itemIds: [564]
    }
    .
    .
    .
]

and second array - items, like this:

items: [{
        act: true
        id: 1234
        name: "Item1"
    },
    {
        act: true
        id: 222
        name: "Item2"
    },
]

How to filter out an array of items whos id isn't equal to any of itemIds from jobs array or that property stat from jobs array isn't equal to 0 ? I tried with three loops, but it dropped out only one item with the same id in a array of jobs. Any help appreciated.

1 Answer 1

1

We are going to use Array.filter to loop over every elements in items and create a new array containing only the items you want to keep.

For each of the values, we are going to see if any job contains in itemIds the code id. To do that, we are going to loop over every job and for every job, we are going to look at the underlying ItemsIds values.

Array.some here will leave as soon at it find something.

const jobs = [{
    name: null,
    id: 612,
    items: [],
    stat: 1,
    itemIds: [223, 1234],
  },
  {
    name: null,
    id: 612,
    items: [],
    stat: 2,
    itemIds: [223, 1234],
  },
  {
    name: null,
    id: 734,
    items: [],
    stat: 2,
    itemIds: [564],
  }
];

const items = [{
    act: true,
    id: 1234,
    name: 'Item1',
  },
  {
    act: true,
    id: 222,
    name: 'Item2',
  },
];

const filteredItems = items.filter(x => jobs.some(y => y.itemIds.includes(x.id) && y.stat !== 1));

console.log(filteredItems);

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

2 Comments

Thanks a bunch, You saved my day ! And if I want to add one more condition, like that stat in array jobs isnt equal to 1, I'll do that like this: const filteredItems = items.filter(x => jobs.some(y => y.itemIds.includes(x.id || y.stat !== 1))) ?
You should insert the additional conditions after the .includes() method. I've edited my snippet with your stat example. Good luck

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.