A
A
AndreyKiyah2021-06-30 22:36:20
React
AndreyKiyah, 2021-06-30 22:36:20

How to filter an array correctly?

The point is this.
I do a fetch, get the members (an array of objects) and put the data into the state.

Next, you need to filter this array by type "view" and not view (one array should be exclusively with elements of the view type and in the other array all elements not of the view type) and then transfer one array to one prop block and the second to the second.

Here's what I did at this stage.
Everything works, the question is, did I do it right ?, or maybe there are some other options on how to organize this all more concisely.
I have experience but not much.
Thank you for your attention.

const viewList = members.filter((member) => member.type === "view");
  const anyList = members.filter((member) => member.type !== "view");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2021-06-30
@Kozack

Yuzai reduce
Like this:

const {view, rest} = arr.reduce(({view, rest}, item) => (item.type === 'view' ? view : rest).push(item), {view, rest}, {view: [], rest: []})

That is, here you create an object with two fields. Then, in one pass through the loop, sort the array by these fields

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question