[Solved] Reduce array of objects to x number of items. Trying to keep at least 2 of specific object property value


So here’s my attempt at solving your issue/request, explanations in the code.

let totalCount = array.length;
let typeCounts = {};

// Separate the array by type and move to an object for easier access
// Result: { product: [{id:0,type:'product',name:'Product 1'},{id:0,type:'product',name:'Product 2'},{id:0,type:'product',name:'Product 3'}], accessory: [ ... ], ... }
array.map((elem) => typeCounts[elem.type] = [...(typeCounts[elem.type] ? typeCounts[elem.type] : []), elem]);

// Keep reducing the amount of array entries by one per type per loop
while(totalCount > 8) {
    let unchanged = true;

    for (let type in typeCounts) {
        if (typeCounts[type].length > 2) {
            typeCounts[type].pop(); // Remove the last entry of that type
            totalCount -= 1;
            unchanged = false;
        }
    }

    // Should it not be possible to reduce the array to 8 items, break
    // Example: Using an array with 9 types, 1 entry per type
    // Ensures we don't get stuck in an infinite loop
    if (unchanged) {
        break;
    }
}

// Join our entries back together
// Result: [{"id":0,"type":"product","name":"Product 1"},{"id":0,"type":"product","name":"Product 2"},{"id":0,"type":"accessory","name":"Accessory 1"},{"id":0,"type":"accessory","name":"Accessory 2"},{"id":0,"type":"accessory","name":"Accessory 3"},{"id":0,"type":"document","name":"Document 1"},{"id":0,"type":"article","name":"Article 1"},{"id":0,"type":"article","name":"Article 2"}]
let reducedArray = Object.values(typeCounts).reduce((acc, value) => acc.concat(value), []);

1

solved Reduce array of objects to x number of items. Trying to keep at least 2 of specific object property value