Filtering Logic Explanation
1. Building the Exclusion Map
excludes.forEach(item => {
if (!mappedArry[item.k]) {
mappedArry[item.k] = [];
}
if (mappedArry[item.k].includes(item.v)) return false;
mappedArry[item.k].push(item.v);
});
This loop constructs mappedArry
, which serves as a map for exclusion criteria. Here’s how it works:
- The
forEach
loop iterates through each object in theexcludes
array. - For each
item
, it checks ifmappedArry
doesn’t already have a keyitem.k
(like ‘color’ or ‘type’). If not, it initializes an empty array for that key. - It then checks if the array for
item.k
already includesitem.v
(like ‘red’, ‘blue’, or ‘tv’). If so, it skips adding it again. - If not included, it adds
item.v
to the array associated withitem.k
.
2. Filtering the Items
return items.filter((item) => {
for (const key in item) {
if (mappedArry[key] && mappedArry[key].includes(item[key])) {
return false;
}
}
return true;
});
After building mappedArry
, the function filters the items
array:
- It uses
Array.filter
to iterate through eachitem
in theitems
array. - For each
item
, it iterates through its properties (for...in
loop). - It checks if
mappedArry[key]
exists (meaning there are exclusion criteria for this property) and if the value ofitem[key]
is included inmappedArry[key]
. - If any property of
item
matches an exclusion criterion, the function returnsfalse
, indicating that this item should be excluded from the filtered result. - If no matches are found, the item is included in the filtered result (
return true
).
Version 2
function excludeItems(items, excludes) {
const exclusionMap = excludes.reduce((map, {k, v}) => {
if (!map[k]) {
map[k] = new Set();
}
map[k].add(v);
return map;
}, {});
return items.filter(item =>
!Object.entries(item).some(([key, value]) =>
exclusionMap[key] && exclusionMap[key].has(value)
)
);
}
Explanation
The excludeItems
function filters an array of objects (items
) based on exclusion criteria provided in another array (excludes
). Here’s how it works:
1. Constructing the Exclusion Map
The function starts by creating an exclusionMap
using the reduce
method. This map is an object where each key corresponds to a property name from the items
objects, and each value is a set of values to exclude for that property.
const exclusionMap = excludes.reduce((map, {k, v}) => {
if (!map[k]) {
map[k] = new Set();
}
map[k].add(v);
return map;
}, {});
For each exclusion criterion in the excludes
array, the function checks if the key (k
) exists in the map
. If not, it initializes a new set for that key. It then adds the value (v
) to the set. Using a set ensures that each value is unique.
2. Filtering the Items
Next, the function filters the items
array. It uses the filter
method to create a new array of items that do not match any exclusion criteria.
return items.filter(item =>
!Object.entries(item).some(([key, value]) =>
exclusionMap[key] && exclusionMap[key].has(value)
)
);
For each item, the function converts it into an array of key-value pairs using Object.entries(item)
. It then checks if any key-value pair matches an exclusion criterion using the some
method. If the exclusionMap
contains the key and the corresponding set contains the value, the item is excluded.
Complete Example
Here’s the complete HTML code with the excludeItems
function and the result display:
JavaScript Methods Used
- The
some()
Method - The
Object.entries()
Method - The
reduce()
Method - The
Set
Object - The
filter()
Method
The some()
Method
The some()
method of Array instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true
if, in the array, it finds an element for which the provided function returns true
; otherwise, it returns false
. It doesn’t modify the array.
Example:
const array = [1, 2, 3, 4, 5];
// Checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// Expected output: true
In this example, some()
checks if there exists at least one even number in the array [1, 2, 3, 4, 5]
, and it returns true
because there are even numbers (2 and 4).
The Object.entries()
Method
The Object.entries()
static method returns an array of a given object’s own enumerable string-keyed property key-value pairs.
Example:
const object1 = {
a: 'somestring',
b: 42,
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// Expected output:
// "a: somestring"
// "b: 42"
In this example, Object.entries()
iterates over the properties of object1
and logs each key-value pair to the console.
The reduce()
Method
The reduce()
method of Array instances executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);
console.log(sumWithInitial);
// Expected output: 10
The Set
Object
The Set
object lets you store unique values of any type, whether primitive values or object references.
const a = new Set([1, 2, 3]);
const b = new Map([
[1, "one"],
[2, "two"],
[4, "four"],
]);
console.log(a.union(b)); // Set(4) {1, 2, 3, 4}
The filter()
Method
The filter()
method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
+ There are no comments
Add yours