Let's say I have 2 javascript/jQuery arrays in my code.
One 2D array that looks like this (console output):
0: {title: 'Freemium', modules: 'Ordering'}
1: {title: 'Standaard', modules: 'Ordering,Invoicing,Cash system'}
and one is a standard 1D array that looks like this (console output):
['Ordering', 'Invoicing', 'Cash system']
I want to compare both arrays to check if the second array matches one of the first arrays. If it does, it needs to return the first array's title column.
To put it into context: Users can select a number of Modules, and when all the selected modules match one of the configured Pricing Plans, the name of the pricing plan is returned.
How would I go about this? I already have both arrays ready in my code, I just need to find a way to compare them and return the first array's title column. I found some solutions to compare two arrays, but never a 2D with a 1D array.
UPDATE:
So my question is perhaps not very well worded or technically correct.
The different plans are added on the page like this:
<div id="packages">
<div class="package" data-title="Freemium" data-modules="Ordering"></div>
<div class="package" data-title="Standaard" data-modules="Ordering,Invoicing,Cash system"></div>
</div>
I am using the following JS code to 'add' the packages to my code:
$("#packages .package").each(function(index) {
var package_title = $(this).data('title');
var package_modules = $(this).data('modules');
packages_array.push({"title": package_title, "modules": package_modules});
});
Each by the user selected module is added to an array like this:
$(".modules .module.active").each(function() {
modules_array.push($(this).data('title'));
});
(The arrays packages_array
and modules_array
are declared at the top of my code)
This is what I have right now, and if someone could point me in the right direction on how to improve my code and how to compare both arrays..
CodePudding user response:
You could first use the array join() function, to convert your selectors into a comma separated string, them use a forEach()
function in your 2d array and compare each module to your new string value
Edit: To account for unsorted arrays you can first order your selectors arrays with sort() and split your modules using split(',')
, order the resulting array, and join()
it, resulting in two sorted strings that can be compared
let objectArray = [{
title: 'Freemium',
modules: 'Ordering'
},
{
title: 'Standaard',
modules: 'Ordering,Invoicing,Cash system'
}
]
let selectorsArray = ["Ordering", "Invoicing", "Cash system"]
let selectorsString = selectorsArray.sort().join()
objectArray.forEach((plan) => {
let sortedModules = plan.modules.split(",").sort().join()
if (sortedModules === selectorsString) console.log("found: " plan.title)
})