Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

351
Views
Changing a value inside the array in a forEach() loop

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>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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);     
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!