group objects in javascript 1

group objects in javascript

function groupBy(arr, prop) {
    const map = new Map(Array.from(arr, obj => [obj[prop], []]));
    arr.forEach(obj => map.get(obj[prop]).push(obj));
    return Array.from(map.values());
}

const data = [{ name: "Display", group: "Technical detals", id: 60, value: 4 }, { name: "Manufacturer", group: "Manufacturer", id: 58, value: "Apple" }, { name: "OS", group: "Technical detals", id: 37, value: "Apple iOS" }];
	
console.log(groupBy(data, "group"));

Here is what the above code is Doing:
1. We create a new Map object, and we pass in an array of arrays.
2. Each array in the array is a key-value pair.
3. The key is the value of the object’s group property.
4. The value is an empty array.
5. We then loop through the array of objects, and we push each object into the array that’s associated with the object’s group property.
6. Finally, we return an array of arrays.

Similar Posts