Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to keep adding to an array every time I run the js file using push but it is not working

I want to save what is returned from a function so when I call it again the functions return keeps saving but instead the saved return changes every time. Is there a way I could save the return of something so when I call it again the previous one is saved and the new one gets added. I wanted to use this when making an object using factory function which one parameter is made randomly, I want to save that random instance but the problem is if the file is called again that random instance is changed. I would be really grateful if anyone can show me a way I can save the output so when I run the js file again it gets added not replaced. For example:

let list = []

const pushingNum = (num) => {
  for (let x = 1; x <= num; x++) {
    list.push(x)
  }
}

pushingNum(2)

console.log(list)

The output I expect is [1,2,1,2,1,2] if I run the file three times but the output is [1,2] even after running the js file multiple times.

I also tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let list = []

const pushingNum = (array) => {
  for (const x of array) {
    list.push(x)
  }
}

pushingNum(['g', 'g', 'g'])

console.log(list)

Still the output is expected [‘g’, ‘g’, ‘g’, ‘g’, ‘g’, ‘g’] after running the file two times but the output is [‘g’, ‘g’, ‘g’].

>Solution :

Store the previous state of the array in localStorage:

let list = JSON.parse(localStorage.getItem("array")) || []

const pushingNum = (num) => {
  for (let x = 1; x <= num; x++) {
    list.push(x)
  }
  localStorage.setItem("array", JSON.stringify(list))
}

pushingNum(2)

console.log(list)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading