Reputation: 1575
If my Array object looks like this :
["pi|sgm", "pi|db", "pi|dlm", "groups|Homesign", "groups|Speakers", "groups|Co-speech Gesture", "pubyear|36"]
How can I split them into multiple array based on their first element. For example, I need the new Array like this:
["pi":["sgm", "db", "dlm"], "groups":["Homesign", "Speakers", "Co-speech Gesture"], "pubyear":["36"]]
Can we do this operation using jQuery?
Upvotes: 1
Views: 100
Reputation: 115242
Use Array#reduce
method with String#split
method.
var data = ["pi|sgm", "pi|db", "pi|dlm", "groups|Homesign", "groups|Speakers", "groups|Co-speech Gesture", "pubyear|36"];
// iterate over the element to reduce to an object
var res = data.reduce(function(obj, v) {
// split the value by delimiter `|`
var spl = v.split('|');
// define the property as an array if already not defined
obj[spl[0]] = obj[spl[0]] || [];
// push the value to the array
obj[spl[0]].push(spl[1]);
// return the object reference
return obj;
// set initial value as an empty object for the result
}, {})
console.log(res);
Or using Array#forEach
method with the same logic.
var data = ["pi|sgm", "pi|db", "pi|dlm", "groups|Homesign", "groups|Speakers", "groups|Co-speech Gesture", "pubyear|36"];
// initialize object for result
var res = {};
// iterate over the element
data.forEach(function(v) {
// split the value by delimiter `|`
var spl = v.split('|');
// define the property as an array if already not defined
res[spl[0]] = res[spl[0]] || [];
// push the value to the array
res[spl[0]].push(spl[1]);
})
console.log(res);
Upvotes: 2