Snippets Collections
  let grouping = items.reduce((obj, item) => {
            const key = item.providerId;
            if (!obj[key]) {
                obj[key] = [];
            }

            obj[key].push(item);

            return obj;
        }, {});
//data
"locations": [
	{
	"name": "Business Academy Australia",
	"lat": -33.8688,
	"lng": 151.2093,
	"website": "https://www.businessacademyaustralia.com.au",
	"tel": "0290198888",
	"email": "info@businessacademyaustralia.com.au",
	"category": "Campus",
	"governmentService": true,
	"formattedLocality": "Sydney, NSW 2000",
	"providerId": "13579",
	"locationId": "4001",
	"registeredTrainerId": "24680",
	"isVetFeeProvider": false,
	"locationTypeId": null,
	"facilities": null,
	"service": null,
	"apprenticeshipTraineeship": true,
	"minimumFee": 1400,
	"maximumFee": 2800,
	"isVetFeeCourse": false,
	"isAvailableOnline": true,
	"isAvailablePartTime": true,
	"deliveryModes": ["In-person"]
	},
	{
	"name": "Entrepreneur Education",
	"lat": -27.4698,
	"lng": 153.0251,
	"website": "https://www.entrepreneureducation.com.au",
	"tel": "0733332222",
	"email": "info@entrepreneureducation.com.au",
	"category": "Campus",
	"governmentService": true,
	"formattedLocality": "Brisbane, QLD 4000",
	"providerId": "98765",
	"locationId": "4002",
	"registeredTrainerId": "13579",
	"isVetFeeProvider": false,
	"locationTypeId": null,
	"facilities": null,
	"service": null,
	"apprenticeshipTraineeship": true,
	"minimumFee": 3800,
	"maximumFee": 4700,
	"isVetFeeCourse": true,
	"isAvailableOnline": false,
	"isAvailablePartTime": false,
	"deliveryModes": ["Online","Hybrid"]
	},
	{
	"name": "Small Business Training Institute",
	"lat": -27.9687807,
	"lng": 153.4066696,
	"website": "https://www.sbtinstitute.com.au",
	"tel": "0388885555",
	"email": "info@sbtinstitute.com.au",
	"category": "Campus",
	"governmentService": false,
	"formattedLocality": "Melbourne, VIC 3000",
	"providerId": "54321",
	"locationId": "4003",
	"registeredTrainerId": "67890",
	"isVetFeeProvider": false,
	"locationTypeId": null,
	"facilities": null,
	"service": null,
	"apprenticeshipTraineeship": false,
	"minimumFee": 2200,
	"maximumFee": 4100,
	"isVetFeeCourse": true,
	"isAvailableOnline": true,
	"isAvailablePartTime": true,
	"deliveryModes": ["In-person"]
	},
  
  
  // using groupby to group locations based on the items in the delivery modes values
  
   	// shows array of arrays
    const getDeliveryItems = items.map((item) => item.deliveryModes);
    console.log({ getDeliveryItems });

    //flatten all the arrays combined into one array and sort each one by their name key
    const flattened = items.flatMap((item) => item.deliveryModes.map((mode) => ({ ...item, mode }))).sort((a, b) => a.name.localeCompare(b.name));

    console.log({ flattened });

    // use grouping to separate out by a new mode key
    let modesGrouped = Object.groupBy(flattened, ({ mode }) => mode);
    console.log({ modesGrouped });
	// In-person: Array(5), Online: Array(4), Hybrid: Array(1)}

    Object.keys(modesGrouped).forEach((key) => {
        // remove the mode key by returing ...rest
        modesGrouped[key] = modesGrouped[key].map(({ mode, ...rest }) => rest);
    });

    console.log({ modesGrouped }); //

   // destructuring
   const { Hybrid: hybrid, ["In-person"]: inPerson, Online: online } = modesGrouped;
   console.log({ hybrid, inPerson, online });







// another example

const apprenticeshipValues = Object.groupBy(items, ({ apprenticeshipTraineeship }) => apprenticeshipTraineeship);

        console.log(apprenticeshipValues[true]);
        console.log(apprenticeshipValues[false]);

        // // desctructuring the objects into an array
        const { true: apprenticeshipTraineeship = [],
               false: nonapprenticeshipTraineeship = [] } = apprenticeshipValues;
        
		console.log({ apprenticeshipTraineeship });
        console.log({ nonapprenticeshipTraineeship });
const items = [
    { name: "Item1", price: 450 },
    { name: "Item2", price: 1500 },
    { name: "Item3", price: 350 },
    { name: "Item4", price: 2000 },
    { name: "Item5", price: 1200 },
    { name: "Item6", price: 300 }
];

const groupedItems = items.reduce((groups, item) => {
    // Define price ranges
    let groupKey = "";
    if (item.price < 500) {
        groupKey = "Under 500";
    } else if (item.price > 1000) {
        groupKey = "Above 1000";
    }

    // Add item to appropriate group
    if (groupKey) {
        if (!groups[groupKey]) {
            groups[groupKey] = [];
        }
        groups[groupKey].push(item);
    }

    return groups;
}, {});

console.log(groupedItems);


// json
{
    "Under 500": [
        { "name": "Item1", "price": 450 },
        { "name": "Item3", "price": 350 },
        { "name": "Item6", "price": 300 }
    ],
    "Above 1000": [
        { "name": "Item2", "price": 1500 },
        { "name": "Item4", "price": 2000 },
        { "name": "Item5", "price": 1200 }
    ]
}
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick'];

    const transportation = data.reduce((total, item) => {

      if(!total[item]){
        total[item] = 0
      }

      total[item]++
      
      return total

    },{})

    console.log(transportation)


/** Dynamic property access (using []):
The square bracket [] syntax is commonly used to access properties of objects dynamically (i.e., using a variable as the property name). This allows you to compute property names at runtime.*/


//get list of buttons and make sure there are no duplicates

function displayButtons(){
    const companies = products.reduce((total, item) => {
       total.push(item.company)
       total = [...new Set(total)]
       return total
    },['All'])
 
    const buttons = companies.map((item) => {
       return `<button class="company-btn">${item}</button>`
    }).join('')
 
    buttonsContainer.innerHTML = buttons
 
 }


 // or we could do this...
 const someBtns = ['all',...new Set(products.map((product) => product.company)),];  
  console.log(someBtns)
function getObjectDataByKey( field, theObject ){
	// get data
	return field.split('.').reduce((o,i)=> o[i], theObject);
}

// a simple object
const myObject = {
  name: 'John',
  lastname: 'Doe',
  data: {
    birthDate: '01/01/1970',
    placeOfBirth: 'San Francisco'
  }
}

// variable representing a key of the object
const field = 'data.birthDate';

console.log ( getObjectDataByKey ( field , myObject ) );
//will print
//01/01/1970

// also simple key will return correct value
console.log ( getObjectDataByKey ( 'name' , myObject) );
//will print
//John
var total = value.reduce((prev, next)=>{
  	return prev +(next.quantity * this.productMap(next.productId).price)
},0 )
star

Wed Feb 12 2025 23:20:21 GMT+0000 (Coordinated Universal Time)

#reducer #reduce
star

Tue Feb 11 2025 04:11:51 GMT+0000 (Coordinated Universal Time)

#grouping #reduce #groupby()
star

Tue Feb 11 2025 03:36:13 GMT+0000 (Coordinated Universal Time)

#grouping #reduce
star

Thu Apr 04 2024 01:28:36 GMT+0000 (Coordinated Universal Time)

#javascript #reduce #counting
star

Mon Dec 19 2022 23:12:50 GMT+0000 (Coordinated Universal Time)

#reduce #array #map #filter
star

Sun Sep 12 2021 09:00:05 GMT+0000 (Coordinated Universal Time)

#reduce #typescript

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension