Higher order functions

Hi! If I have such an array like this:

let assortment = [
{name: “banana”, code: 02696, bestbefore: 02.09.2019},
{name: “toothbrush”, code: 08568, bestbefore: 17.12.2030},
{name: “soap”, code: 05263, bestbefore: 28.02.2022},
{name: “pen”, code: 06327, bestbefore: 03.06.2035}]

how can I get those items which includes for example 8 in it (toothbrush, soap)?

Hi.
Well, what would be your steps? Are you familiar with HOFs? What other ways there are to solve this?

Yes, actually I’m learning currently these functions. I guess I should use map and/or sort method, but I don’t know how can I get the result if I should examine two properties at the same time: code and bestbefore. Is it needed in addition to use test method or something similar method?

You’ll have to check for each property one by one. So you could start by filtering your array and then checking if each value in your object being filtered has ‘8’ in it and return it if it has. You’re right in that regard that you need some additional code to check every property of an object but it’s easy with a simple for loop. You can, of course, test values of properties with regexes, or check for presence of ‘8’ with other methods. Either way you need a check for ‘8’.
The difference between map and filter is quite distinctive. With map you take each and every value in the array and do something with that value, and return a (new) modified array. While possible in your problem, filter is much more suitable because it filters out - dismiss values that don’t qualify for your check, and return only what you need. sort wouldn’t do anything valuable here, you would just sort your objects in some particular order.

1 Like

If you know how to use filter, and the datas you want to check are strings you can use String.prototype.includes() and the OR operator so you can check both properties in the same filter method

1 Like