I have a function that will accept 3 arguments; an array of data, a key and a partial value. I want to group the results by a value that may be in each objects nested array. It looks like my code is working, but I'm wondering if refactoring to use reduce would be better. Here is what I have:
const arr = [
{
"id": "vghjnbghjkoijhjnmkjhjk",
"region": "US",
"tags": ["tag1:bvghjhgh","tag2:bvghjkjnm","tag3:vghjbghj"]
},
{
"id": "cvbhyt56789-mnbvghyu76",
"region": "US",
"tags": ["tag1:bvghjhgh"]
},
{
"id": "ghjkjnbhjnbhjkmnhjkmjk",
"region": "US",
"tags": ["tag2:bvghjkjnm"]
},
{
"id": "ghjkjnbhjnbhjkmnhjkmjk",
"region": "US",
"tags": []
},
{
"id": "bghjkjnbghjkjnhjnbhjhj",
"region": "CA",
"tags": ["tag1:bvghjhgh","tag3:vghjbghj"]
}
];
The expected results are as follows, based on a key of tags and a value of tag1:
[
[
{
"id": "vghjnbghjkoijhjnmkjhjk",
"region": "US",
"tags": ["tag1:bvghjhgh","tag2:bvghjkjnm","tag3:vghjbghj"]
},
{
"id": "cvbhyt56789-mnbvghyu76",
"region": "US",
"tags": ["tag1:bvghjhgh"]
},
{
"id": "bghjkjnbghjkjnhjnbhjhj",
"region": "CA",
"tags": ["tag1:bvghjhgh","tag3:vghjbghj"]
}
],
[
{
"id": "ghjkjnbhjnbhjkmnhjkmjk",
"region": "US",
"tags": ["tag2:bvghjkjnm"]
},
{
"id": "ghjkjnbhjnbhjkmnhjkmjk",
"region": "US",
"tags": []
},
]
]
Here is my current function:
function groupData(arr, key, value) {
const grouped = {};
const remaining = [];
for (const obj of arr) {
const index = obj[key].findIndex(elem => elem.includes(value));
if (index > -1) {
const groupByKey = obj[key][index];
if (grouped.hasOwnProperty(groupByKey)) {
grouped[groupByKey].push(obj);
} else {
grouped[groupByKey] = [obj];
}
} else {
remaining.push(obj);
}
}
return [Object.values(grouped).flat(), noMatch];
}