JavaScript: Get a list of elements that exist in both arrays, after applying the provided function to each array element of both
JavaScript fundamental (ES6 Syntax): Exercise-210 with Solution
Common Elements After Mapping
Write a JavaScript program to get a list of elements in both arrays, after applying the provided function to each array element of both.
- Use Array.prototype.filter() and Array.prototype.findIndex() in combination with the provided comparator to determine intersecting values
Sample Solution:
JavaScript Code:
// Define a function 'intersectionBy' that computes the intersection of two arrays based on a transformation function
const intersectionBy = (a, b, fn) => {
// Create a Set 's' containing the transformed elements of array 'b' using the provided function 'fn'
const s = new Set(b.map(x => fn(x)));
// Filter elements from array 'a' if their transformed values exist in the Set 's'
return a.filter(x => s.has(fn(x)));
};
// Test the 'intersectionBy' function by finding the intersection of two arrays using the 'Math.floor' function as the transformation function
console.log(intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor));
// Output: [2.1]
Output:
[2.1]
Flowchart:
Live Demo:
See the Pen javascript-basic-exercise-210-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to get a list of elements that exist in both arrays, using a provided comparator function.
Next: Write a JavaScript program to get a list of elements that exist in both arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics