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

170
Views
how to push value to array

I have this function

getVal(item){
  var data = [];
  data.push(item);
  console.log(data);
}

the value of the variable item is:

4.9000
6.7000

I want to insert into an array , but the result in my console is this:

4.9000
6.7000

I want the output to be this: [4.9000, 6.7000 ]

Do I have to merge first? Or maybe my push technique is wrong?

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

0

Remove data from getVal scope. here you make a new array for each execution

var data = [];
getVal(item){
  data.push(item);
  console.log(data);
}
about 4 years ago · Juan Pablo Isaza Report

0

Your logic with push function is right. But the problem is every time the function run, you clear all the previous value.

An alternative solution is to declare it outside or you could run a for loop:

let data = [];
function getVal(item){
  data.push(item);
}
getVal(1)
getVal(2)
  console.log(data);

Run a for loop:

let data = [];

 function getVal(item){
  let data = []  
  for(let i in item){
  data.push(i);
  }
  console.log( data)
}

getVal([1,2,3])

about 4 years ago · Juan Pablo Isaza Report

0

You have to move the initialization of data out of the function body. You can avoid the global variable using a closure and an IIFE

const getVal = (() => {
  const data = [];
  return (item) => {
    data.push(item);
    console.log(data);
  }
})();

Example:

const getVal = (() => {
  const data = [];
  return (item) => {
    data.push(item);
    console.log(data);
  }
})();

getVal(1);
getVal(2);

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!