Say I have an array of objects that looks like this, which represents all records in a database:
let data1 = [
{"name": "ethan", "age": 18, "class": "A", "grade": 83},
{"name": "sam", "age": 13, "class": "A", "grade": 43},
{"name": "mark", "age": 14, "class": "D", "grade": 33},
{"name": "dick", "age": 14, "class": "B", "grade": 85},
{"name": "luke", "age": 15, "class": "A", "grade": 93},
{"name": "adam", "age": 5, "class": "C", "grade": 55},
]
I want to perform a join based on some column names, "name" and "class", since they are the primary keys.
let cols = ["name", "class"];
now I have another array of objects
let data2 = [
{"name": "ethan", "age": 48, "class": "A", "grade": 49},
{"name": "dick", "age": 24, "class": "B", "grade": 43},
]
I want a function that would loop through each record in data1, then check if the "name" value and "class" value match any of the records in data2 that has the same values at same columns. If yes, then the data1 record would be pushed to a new array. And the new array would be return at the end of the function.
for example, the function would start with first item in data1, {"name": "ethan", "age": 18, "class": "A", "grade": 83}, and look for a matching record in data2 that also with name "ethan" and class "A", ignoring value from other columns, if a match is found, then {"name": "ethan", "age": 18, "class": "A", "grade": 83} is pushed to the output array.
here is how I imagined what the function would look like, I would like the keys checked on to be passed in as an array so the solution is dynamic.
function getSubset(cols, data1, data2) {
let output = [];
for (let i = 0; i < data1; i++) { //loop through each item in data1
let item = data1[I];
//checks here
//if match found in data2, push to output array
}
return output;
}
//expected output =
//[ {"name": "ethan", "age": 18, "class": "A", "grade": 83},
// {"name": "dick", "age": 14, "class": "B", "grade": 85},
//]
data2for each row to compare, and loop trough thecolsto check whether all the respective property values are the same in both items. What exactly do you have trouble with?