Expanding Array of Objects Based on a Specified Quantity

In some scenarios, you might have an array of objects representing items in an order or list. Each item might have a quantity or count, and you need to expand this array so that each item appears multiple times based on its quantity.

// Sample array of objects representing order line details
let orderLineDetails = [
    {
        id: "12345",
        item: "Item A",
        quantity: 3,
        weight: 2,
        dimensions: {
            length: 5,
            width: 3,
            height: 2
        },
        memo: "Some notes about Item A"
    },
    {
        id: "67890",
        item: "Item B",
        quantity: 2,
        weight: 4,
        dimensions: {
            length: 6,
            width: 4,
            height: 3
        },
        memo: "Some notes about Item B"
    }
];


// Function to expand array based on the quantity of each item
let expandedOrderLineDetails = orderLineDetails.flatMap(item =>
    Array.from({ length: item.quantity }, () => ({
        ...item,
        quantity: 1 // Set each expanded item’s quantity to 1
    }))
);


console.log("Expanded Order Line Details:", expandedOrderLineDetails);

Explanation

  • Input: The original array orderLineDetails contains objects where each object represents an item in an order. Each item has properties like ,id, item, quantity, weight and dimensions.
  • Transformation: The flatMap method is used to expand each item in the array. For each item, we create an array with the same item repeated based on its quantity. The quantity is then reset to 1 for each expanded item.
  • Output: The result is a new array where each item appears as many times as specified by its original quantity. This is useful in scenarios where you need to process each unit of an item individually.

Leave a comment

Your email address will not be published. Required fields are marked *