I have managed to split an array into separate groups based on key value. What I want to achieve is to turn these groups which can be more or less into an array, so my groups become [[Regio__c],[Categorie__c]]
instead of {Regio__c:[],Categorie__c:[]}
. This with plain javascript no libraries.
I tried: return [key].concat.split;
this returns undefined.
Below is my code in a snippet
var filter = [{
"Id": "120",
"arrayPicklist": "Categorie__c"
}, {
"Id": "121",
"arrayPicklist": "Regio__c"
},
{
"Id": "122",
"arrayPicklist": "Categorie__c"
}, {
"Id": "123",
"arrayPicklist": "Regio__c"
},
{
"Id": "121",
"arrayPicklist": "Regio__c"
}
]
function splitArrayByValue(arr, key) {
var split = {};
for (var i = 0; i < arr.length; i++) {
var p = arr[i][key];
if (!split[p]) {
split[p] = [];
}
split[p].push(arr[i])
}
return split;
}
var buckets2 = splitArrayByValue(filter, 'arrayPicklist');
console.log(buckets2);
You almost there, you need to get the values. An alternative is using the function Object.values
var filter = [{ "Id": "120", "arrayPicklist": "Categorie__c" }, { "Id": "121", "arrayPicklist": "Regio__c" }, { "Id": "122", "arrayPicklist": "Categorie__c" }, { "Id": "123", "arrayPicklist": "Regio__c" }, { "Id": "121", "arrayPicklist": "Regio__c" }]
function splitArrayByValue(arr, key) {
var split = {};
for (var i = 0; i < arr.length; i++) {
var p = arr[i][key];
if (!split[p]) {
split[p] = [];
}
split[p].push(arr[i])
}
return Object.values(split);
}
var buckets2 = splitArrayByValue(filter, 'arrayPicklist');
console.log(buckets2);
You can use the function reduce
to group and then the function Object.values
to get the desired output.
var filter = [{"Id":"120","arrayPicklist":"Categorie__c"},{"Id":"121","arrayPicklist":"Regio__c"},{"Id":"122","arrayPicklist":"Categorie__c"},{"Id":"123","arrayPicklist":"Regio__c"},{"Id":"121","arrayPicklist":"Regio__c"}];
var result = Object.values(filter.reduce((a, {Id, arrayPicklist}) => {
(a[arrayPicklist] || (a[arrayPicklist] = [])).push({Id, arrayPicklist});
return a;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just return Object.values(split)
instead of split
in splitArrayByValue function.
var filter = [{"Id":"120","arrayPicklist":
"Categorie__c"},{"Id":"121","arrayPicklist":"Regio__c"},
{"Id":"122","arrayPicklist":"Categorie__c"},{"Id":"123","arrayPicklist":"Regio__c"},
{"Id":"121","arrayPicklist":"Regio__c"}]
function splitArrayByValue(arr, key) {
var split = {};
for (var i=0; i<arr.length; i++) {
var p = arr[i][key];
if (!split[p]) { split[p] = []; }
split[p].push(arr[i])
}
return Object.values(split);//<---- just return Object.values(split) instead of split
}
var buckets2 = splitArrayByValue(filter,'arrayPicklist');
console.log(buckets2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With