Vassil_Iliev

HighOrder

Apr 30th, 2022
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Implement unique - return the unique elements, based on a passed selector
  3.     const unique = (arr, selector) => {}
  4.     const numbers = [1,1,3,2,1,2,3];
  5.     console.log(unique(numbers, n => n)); // [1, 3, 2]
  6.    
  7.    const pets = [
  8.         { type: 'dog', name: 'sharo' },
  9.         { type: 'cat', name: 'maca' },
  10.         { type: 'dog', name: 'balkan' }
  11.     ];
  12.    
  13.     const uniqueByType = unique(pets, p => p.type);
  14.     // [{ type: 'dog', name: 'sharo' }, { type: 'cat', name: 'maca' }]
  15.  */
  16.  
  17. const pets = [
  18.     { type: 'dog', name: 'sharo' },
  19.     { type: 'cat', name: 'maca' },
  20.     { type: 'dog', name: 'balkan' }
  21. ];
  22.  
  23. const unique = (arr, selector) => {
  24.     const selected = arr.map(selector)
  25.  
  26.     const result = selected.reduce((acc, el) => {
  27.         if (typeof arr[0] != 'object') {
  28.             if (!acc.includes(el)) {
  29.                 acc = [...acc, el]
  30.             }
  31.         } else {
  32.             if (!acc.some(obj => obj.type === el)) {
  33.                 acc.push({ type: el, name: arr.find(e => e.type === el).name })
  34.             }
  35.         }
  36.  
  37.         return acc;
  38.     }, [])
  39.  
  40.     return result
  41. }
  42.  
  43. console.log(unique([1, 1, 2, 1, 3, 4, 5], n => n))
  44. console.log(unique(pets, n => n.type))
Advertisement
Add Comment
Please, Sign In to add comment