Home > front end >  How do I sequentially add to a field inside each customer?
How do I sequentially add to a field inside each customer?

Time:12-10

When I click the button, I should add it to the itemSold field. But the example should be like this:

  1. I click any button. The first element in the 'itemSold' array of the 1st customer is null. That's why he added it here.
  2. I click any button. The first element in the 'itemSold' array of the 2nd customer is null. That's why he added it here.
  3. I click any button. The second element in the 'itemSold' array of the 1st customer is null. That's why he added it here.
  4. I click any button. The second element in the 'itemSold' array of the 2nd customer is null. That's why he added it here.

let customers = [{
    active: true,
    id: 1,
    product: {
      itemSold: [null, null],
    },
  },
  {
    active: true,
    id: 2,
    product: {
      itemSold: [null, null],
    },
  },
];


let products = [
{id:1,name : 'car'},
{id:2,name : 'home'},
{id:3,name : 'phone'},
{id:4,name : 'fly'},
]
let productsContainer = document.querySelector(".productsContainer");


let productHTML = ``;
products.map((product) => {
  return (productHTML  = `<button  id=${product.id}>${product.name}</button>`);
});


productsContainer.innerHTML = productHTML;
<div  >
</div>

CodePudding user response:

So to be - universal without storing any state it could be something like this

function addItem(item) {
 const nullIndexes = customers.map(c => c.product.itemSold.indexOf(null));
 if(nullIndexes.every(i => i == -1)) return;
 const minIndex = Math.min(...nullIndexes.filter(i => i != -1))
 for(var customer of customers) {
     if(customer.product.itemSold[minIndex] === null) {
         customer.product.itemSold[minIndex] = item;
         break;
     }
 }    
}

Some explanation

  1. We need to know if there is any nulls left in arrays, for that we need to get indexes of nulls for each of the arrays customers.map(c => c.product.itemSold.indexOf(null));
  2. Now we need to check, if nulls not found (all of the indexes are -1) then we done if(nullIndexes.every(i => i == -1)) return;
  3. Then we need to get the correct index of value we need to replace, for that we need to have the least index that we found above, but not counting -1 (because -1 means that that particular array is already full) const minIndex = Math.min(...nullIndexes.filter(i => i != -1))
  4. Now, all we have to do is to go over the customers and find that particular one that has null in the index we determined above and replace it.

Don't get me wrong - this is most likely not the best optimal way, but it is a solution

  • Related