2

Message: This is a function I'm going to implement in my very first project (Which is a point-of-sale system) using Vue Js and I wrote this function using pure JavaScript to simplify this question. So I'd be really grateful if somebody could help me with this problem so I can continue building my practice project. Thanks ❤️

My code explanation: I have an empty array called newArray.And an array called mainArray with some records. And I've included a button with an onClick event that triggers the function clicked() with an argument passed to it, which is 2 in this case.

What I'm expecting to get: I want to check for a record inside the newArray which contains an id with 2. If such a record is found, I want to add the stock value by 1 in the record. If such a record is not found inside the newArray loop through the mainArray and copy the record which has the id of 2 and add it to the newArray and reset the stock to 1 (So when we click the button again, the record which has id 2 is already there inside the newArray, therefore, I want to add 1 to it, So the stock: 2 now). I have attempted on this problem, and I have attached the code.

Summary according to my project: I have looped through mainArray in my project, so each record has a button with clicked() function, with an attribute called productId, productId is passed as the argument to the clicked() function, I'm expecting: If I click on a button it takes productId as the argument and the function loops through the newArray finding for a record which has id equal to the productId If such record is there add stock by 1. If such record is not there grab the record from the mainArray which has the id equal to the productId value and put inside the newArray by setting the stock value to 1 (stock: 1). So when I click the same button which has the same attribute value it will add 1 to the stock in the record of the same value equal to the id inside the newArray (therefore the stock: 2 now) If again click stock will be stock: 3 so on adding by 1.

function clicked(inp){
 const newArray = [];
 const mainArray = [
     { id: 1, name: "Shoes",stock: 5, price: 10 },
     { id: 2, name: "Bag",stock: 10, price: 50 },
 ];
 
newArray.forEach((item) => {
  if(inp == item.id){
    item.days = item.days + 1;
  } else {
    mainArray.forEach((element) => {
      if(inp == element.id){
        newArray.push(element);
      }
    });
  }
 });
 
 console.log(newArray);
    
}
<button id="1" onClick="clicked(2)">Click me</button>

4
  • Your new array will always be empty like this. Each time the function is called, within the scope of the function it's a new array that is empty so your foreach will not execute. Commented Jun 16, 2022 at 7:05
  • So here's some simplified logic, if the new array is empty, find and add the product to the array. Else use your existing logic. Commented Jun 16, 2022 at 7:10
  • @Onboardmass doesn't the else statement execute thereafter? Commented Jun 16, 2022 at 7:10
  • Thereafter? I'm assuming you mean whenever the cart/new array isn't empty, then yes. Commented Jun 16, 2022 at 7:15

4 Answers 4

3

Suggestion : move newArray outside the clicked function as it is going to update on click.

Implementation : You can use Array.filter() method on newArray to check if record as per the input id is available or not and then by using Array.find() you can do filtering on the mainArray if there is no data in newArray.

Live demo :

const newArray = [];

function clicked(inp){
  const mainArray = [
    { id: 1, name: "Shoes",stock: 5, price: 10 },
    { id: 2, name: "Bag",stock: 10, price: 50 },
  ];

  const findInNewArr = newArray.filter(item => inp === item.id);

  if (findInNewArr.length) {
    newArray[0].stock += 1;
  } else {
    const findInMainArray = mainArray.find(element => inp === element.id);
    if (findInMainArray) {
      findInMainArray.stock = 1;
      newArray.push(findInMainArray);
    }
  }

  console.log(newArray);

}
<button id="1" onclick="clicked(2)">Click me</button>

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is great this gave me the idea. And I have updated this a little bit to make it dynamic this is what I really expected 👉 jsfiddle.net/4eh51ano/9 .Somehow your answer helped me a lot in this case.Thank you so much ❤️
1

This is what I really expected (Thanks to Rohìt Jíndal for giving me the idea of doing this)

const newArray = [{ id: 1, name: "Shoes",stock: 1, price: 10 }];

function clicked(inp){
  const mainArray = [
    { id: 1, name: "Shoes",stock: 5, price: 10 },
    { id: 2, name: "Bag",stock: 10, price: 50 },
  ];

  const findInNewArr = newArray.filter(item => inp === item.id);

  if (findInNewArr.length > 0) {
    newArray.forEach((element) => {
      if(element.id === inp) {
        element.stock += 1;
      }
    });
  } else {
    const findInMainArray = mainArray.find(element => inp === element.id);
    if (findInMainArray) {
      findInMainArray.stock = 1;
      newArray.push(findInMainArray);
    }
  }

  console.log(newArray);

}
<button id="1" onclick="clicked(2)">Click me</button>

Comments

1

In your code forEach function will not be executed, because newArray is empty, so there is nothing to iterate through.

You might use findIndex to loop through newArray and then check if index is greater than -1. That would mean that array contains object with specified id.

function clicked(inp){
  const newArray = [];
  const mainArray = [
    { id: 1, name: "Shoes",stock: 5, price: 10 },
    { id: 2, name: "Bag",stock: 10, price: 50 },
  ];
         
  const inputIndex = newArray.findIndex((item) => item.id === inp);
    
  if (inputIndex > -1) {
    newArray[inputIndex].stock = newArray[inputIndex].stock + 1;
  } else {
    mainArray.forEach((element) => {
      if(inp == element.id){
        newArray.push(element);
      }
    });
  }
         
  console.log(newArray);     
}

Comments

0

you can find inp in 2 arrays, then update or create new element for newArray

const newArray = [];
const mainArray = [{
    id: 1,
    name: "Shoes",
    stock: 5,
    price: 10
  },
  {
    id: 2,
    name: "Bag",
    stock: 10,
    price: 50
  },
];

function clicked(inp) {
  let exist = newArray.find(ele => ele.id === inp)
  if(exist) {
    exist.stock++
  } else {
    let {id,name, price} = mainArray.find(ele => ele.id === inp)
    exist = {id,name, price, stock: 1};
    newArray.push({...exist})
  }
  console.log('newArray :', newArray)
  console.log('mainArray :', mainArray)
}
<button id="1" onClick="clicked(2)">Click me</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.