I am working on a menu that contains three groups of checkboxes to filter items on a webpage. The groups are labeled as store
, city
, and level
. When any checkbox is checked within these groups, the value gets added to the corresponding array in an object structured like this:
items = {
store: [],
city: [],
level: []
}
By default, all items are visible and no checkboxes are checked. Upon checking or unchecking a box, the items get filtered first by store
and city
, followed by further filtering based on level
. If no level
boxes are checked, all levels are displayed; however, if any are checked, only the checked store/city
s of the checked level
s are shown.
For example, the object could be represented as:
itms = {
store: [
'north',
'evans',
'dodge'
],
city: [
'boston',
'miami',
],
level: [
'gold',
'silver'
]
}
The desired formatted string should look like this:
.north.gold,.north.silver,.evans.gold,.evans.silver,.dodge.gold,.dodge.silver,.boston.gold,.boston.silver,.miami.gold,.miami.silver,
- order doesn't matter
If the object were:
items = {
store: [
'north',
'evans',
'dodge'
],
cite: [ 'miami' ],
level: []
}
The resulting string would be:
.north,.evans,.dodge,.miami
To generate the correctly formatted string from the object, currently I am using inefficient iteration methods:
for (let [key, value] of Object.entries(items)) {
value.forEach(item => {
if(key !== 'level') {
finalSelectors.push(`.${item}`);
if (key === 'city') {
finalSelectors.push(`.${item}_child`);
}
}
});
}
let selectorsArr = finalSelectors;
const reFinalSelectors = [];
const selectedLevels = items.level;
if(selectedLevels.length) {
if(items.city.length || items.location.length) {
finalSelectors.forEach(selector => {
selectedLevels.forEach(level => {
reFinalSelectors.push(`.${level}${selector}`);
});
});
} else {
selectedLevels.forEach(level => {
reFinalSelectors.push(`.${level}`);
});
}
selectorsArr = reFinalSelectors;
}
I am new to array functions and unsure about more advanced ones like Array.reduce()
. Any guidance or assistance on how to improve efficiency would be greatly appreciated.