I have an array with multiple objects. I'd like to split this array to multiple arrays. The criteria to split is the item continent.
MyArray = [{continent:"europe", fruit:"orange", value:2},
{continent:"asia", fruit:"banana", value:2},
{continent:"europe", fruit:"apple", value:2},
{continent:"asia", fruit:"apple", value:5}
];
Output:
[
[{continent:"europe", fruit:"orange", value:2},
{continent:"europe", fruit:"apple" value:2}
], [
{continent:"asia", fruit:"banana", value:2},
{continent:"asia", fruit:"apple" value:5}]
];
You could search for the array with the same continent and update this array or push a new array with the actual object.
var array = [{ continent: "europe", fruit: "orange", value: 2 }, { continent: "asia", fruit: "banana", value: 2 }, { continent: "europe", fruit: "apple", value: 2 }, { continent: "asia", fruit: "apple", value: 5 }],
grouped = array.reduce(function (r, o) {
var group = r.find(([{ continent }]) => continent === o.continent)
if (group) {
group.push(o);
} else {
r.push([o]);
}
return r;
}, []);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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