Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Implement unique - return the unique elements, based on a passed selector
- const unique = (arr, selector) => {}
- const numbers = [1,1,3,2,1,2,3];
- console.log(unique(numbers, n => n)); // [1, 3, 2]
- const pets = [
- { type: 'dog', name: 'sharo' },
- { type: 'cat', name: 'maca' },
- { type: 'dog', name: 'balkan' }
- ];
- const uniqueByType = unique(pets, p => p.type);
- // [{ type: 'dog', name: 'sharo' }, { type: 'cat', name: 'maca' }]
- */
- const pets = [
- { type: 'dog', name: 'sharo' },
- { type: 'cat', name: 'maca' },
- { type: 'dog', name: 'balkan' }
- ];
- const unique = (arr, selector) => {
- const selected = arr.map(selector)
- const result = selected.reduce((acc, el) => {
- if (typeof arr[0] != 'object') {
- if (!acc.includes(el)) {
- acc = [...acc, el]
- }
- } else {
- if (!acc.some(obj => obj.type === el)) {
- acc.push({ type: el, name: arr.find(e => e.type === el).name })
- }
- }
- return acc;
- }, [])
- return result
- }
- console.log(unique([1, 1, 2, 1, 3, 4, 5], n => n))
- console.log(unique(pets, n => n.type))
Advertisement
Add Comment
Please, Sign In to add comment