skip to Main Content

I am trying to create the following:

I have an array with a quantity n of items and as more items are added, I want them to be assigned to each object but taking into account the percentage of assignment in each object.

const items = []
const obj1 = {id: 1, allocationPercentage: 40, items: []}
const obj2 = {id: 2, allocationPercentage: 20, items: []}
const obj3 = {id: 3, allocationPercentage: 40, items: []}

If I add 5 items to the array, then it would look something like this:

const items = ["item1", "item2", "item3", "item4", "item5"]

const obj1 = {id: 1, allocationPercentage: 40, items: ["item1", "item2"]}
const obj2 = {id: 2, allocationPercentage: 20, items: ["item3"]}
const obj3 = {id: 3, allocationPercentage: 40, items: ["item4", "item5"]}

The percentage of allocation in each object could vary.

2

Answers


  1. const items = ["item1", "item2", "item3", "item4", "item5"]
    const obj1 = {id: 1, allocationPercentage: 40, items: []}
    const obj2 = {id: 2, allocationPercentage: 20, items: []}
    const obj3 = {id: 3, allocationPercentage: 40, items: []}
    // group objs in an array
    const objs = [obj1, obj2, obj3]
    
    let cursor = 0
    for (const obj of objs) {
      // calculate number of items to add to the array per object
      const numberOfItems = Math.floor(obj.allocationPercentage / 100 * items.length)
      // get the items
      const itemsToAdd = items.slice(cursor, cursor + numberOfItems)
      // push them to the items
      obj.items.push(itemsToAdd)
      // remember to move the cursor
      cursor += numberOfItems
    }
    
    console.log(objs)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search