JavaScript: Get all unique values of an array, based on a provided comparator function
JavaScript fundamental (ES6 Syntax): Exercise-108 with Solution
Unique Values by Comparator
Write a JavaScript program to get all unique values of an array, based on a provided comparator function.
- Use Array.prototype.reduce() and Array.prototype.some() for an array containing only the first unique occurrence of each value, based on the comparator function, fn.
- The comparator function takes two arguments: the values of the two elements being compared.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
// Define a function 'uniqueElementsBy' to return unique elements from an array based on a comparison function.
const uniqueElementsBy = (arr, fn) =>
// Use reduce to iterate over the array 'arr'.
arr.reduce((acc, v) => {
// If the accumulator 'acc' does not contain any element that satisfies the comparison function 'fn' with the current element 'v', add 'v' to the accumulator.
if (!acc.some(x => fn(v, x))) acc.push(v);
// Return the accumulator.
return acc;
}, []);
// Test the 'uniqueElementsBy' function with an example.
console.log(uniqueElementsBy(
[
{ id: 0, value: 'a' },
{ id: 1, value: 'b' },
{ id: 2, value: 'c' },
{ id: 1, value: 'd' },
{ id: 0, value: 'e' }
],
(a, b) => a.id == b.id
));
Output:
[{"id":0,"value":"a"},{"id":1,"value":"b"},{"id":2,"value":"c"}]
Flowchart:
Live Demo:
See the Pen javascript-basic-exercise-108-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to get all unique values (form the right side of the array) of an array, based on a provided comparator function.
Next: Write a JavaScript program to get the nth element of an given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-108.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics