Home > front end >  Changing a value inside the array in a forEach() loop
Changing a value inside the array in a forEach() loop

Time:06-16

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>

CodePudding user response:

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>

CodePudding user response:

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>

CodePudding user response:

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);     
}

CodePudding user response:

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>

  • Related