Filter array for the first three occurrences of a string?

Hey guys, I’m working on a project and trying to filter an array of art mediums down to 9 elements in a new array to display on the main splash page. I want the first three boxes to be the medium ‘Art’, which is anything that isn’t ‘Jewelry’ or ‘Photography’. I have this currently, an array of strings of mediums…how can i filter the first three that AREN’T jewelry and photography, then filter the first 3 jewelry, then last photography. And finally, put them in one array and display…I have thought of filter, reduce, includes, but can’t figure it out.

1 Like

Use a loop, it’ll be much easier. The iterator functions want to go over your whole collection every time, they aren’t designed to bail out once you’re done (which is what you want), or switch how they work halfway through.

SET artCounter to zero
SET jewelleryCounter to zero
SET photographyCounter to zero
SET output to empty array
FOR medium of media
  # your conditions here
  PUSH medium to output IF condition met
  INCREMENT art/jewellery/photography counter
ENDFOR
RETURN output

You can also use reduce, reducing the array into something like {art: [], jewellery: [], photography: []}, then concatenating that once you’re done, but as I say, there is no way to bail out, and really you want to stop iterating as soon as you’ve got the output you want (there is no point continuing after that point).

1 Like

I’ll try it and will let ya know.

Or you could reverse the thought process:

let jewelryList = /* filter the list to just the "Jewelry" */,
     photogList = /* filter the list to just the "Photography" */,
     artListList = /* filter the list to include anything NOT in the other two lists */,
     finalList = /* concat slices of the three arrays above */

I actually tinkered with this as a repl, seems to work nicely.

Understandable, if it keeps going, you just allocate more memory?

Ooo point. Hadn’t even considered that. Hmm…

Yeah, there is that: the iterator functions that you’re looking generally have to go over the array each time, so if you chain them you’ll go over multiple times (albeit on a smaller array each time). Performance-wise it isn’t likely to matter too much for this usecase, but it doesn’t hurt to keep that in mind.

Tbh though, thinking about it, it’s more the readability aspect of it: the logic here is so specific that it makes sense to write a loop based function that does exactly what you need rather than trying to fight with the generalisations that are the iterator functions