Let’s say, we have an array of objects like this −
Example
const arr = [ {text:'use'}, {text: 'secur'}, {text: 'form'}, {text: 'user'}, {text: 'users'}, {text: 'form'}, {text: 'secur'}, {text: 'sec'}, {text: 'users'}, {text: 'secu'}, {text: 'secur'}, {text: 'for'}, {text: 'form'} ]
Our job is to write a function that takes in this array and a number n and the function should return an array of n objects which have the longest string value for the text key and all the objects should have a unique value for the text key. If there doesn’t exist n unique objects, then we should return all unique objects.
Therefore, let’s write the code for this function −
Example
const arr = [ {text: 'use'}, {text: 'secur'}, {text: 'form'}, {text: 'user'}, {text: 'users'}, {text: 'form'}, {text: 'secur'}, {text: 'sec'}, {text: 'users'}, {text: 'secu'}, {text: 'secur'}, {text: 'for'}, {text: 'form'} ]; const sorter = (a, b) => { return b.text.length - a.text.length; } const longestUnique = (arr, num) => { const copy = arr.slice(); copy.sort(sorter); const map = new Map(); const uniqueCopy = copy.filter(el => { const exists = map.get(el.text); if(exists){ return false; }; map.set(el.text, 1); return true; }); return uniqueCopy.splice(0, num); } console.log(longestUnique(arr, 4)); console.log(longestUnique(arr, 12));
Output
The output in the console will be −
[ { text: 'secur' }, { text: 'users' }, { text: 'form' }, { text: 'user' } ] [ { text: 'secur' }, { text: 'users' }, { text: 'form' }, { text: 'user' }, { text: 'secu' }, { text: 'use' }, { text: 'sec' }, { text: 'for' } ]