Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Multiple filters over a list O(2n)
- const things = ['apple', 'orange', 'cat', 'dog'];
- const animals_filtered = things.filter(item => item === 'cat' || item === 'dog');
- const fruit_filtered = things.filter(item => item === 'apple' || item === 'orange');
- // One reduce over list O(n):
- const {animals, fruit} = things.reduce((curr, item) => {
- console.log('Item', item);
- if (item === 'cat' || item === 'dog') {
- curr.animals.push(item);
- }
- if (item === 'apple' || item === 'orange') {
- curr.fruit.push(item);
- }
- return curr;
- }, { animals: [], fruit: []});
- console.log('Animals:', animals_filtered, '&', animals);
- // "Animals:" ["cat", "dog"] "&" ["cat", "dog"]
- console.log('Fruit:', fruit_filtered, '&', fruit);
- //"Fruit:" ["apple", "orange"] "&" ["apple", "orange"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement