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

260
Views
JS How to save the result of a for loop as an array?
const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = [];

for (let i = 0; i < cars.length; i++) {
  const i = 'hi';
  console.log(i);
}

the result of this code would be:

hi
hi
hi
hi
hi
hi

how can I save this result to a variable as an array? The returned value should be: ['hi','hi','hi','hi','hi','hi']

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

0

The best thing you can make use of is map operator

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = cars.map(car => 'hi');
about 4 years ago · Juan Pablo Isaza Report

0

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = [];
const x = 'hi';

for (let i = 0; i < cars.length; i++) {
  arr.push(x);
}
about 4 years ago · Juan Pablo Isaza Report

0

Another option using Array.from()

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = Array.from(cars, _ => "hi");

const cars = ['BMW', 'Volvo', 'Saab', 'Ford', 'Fiat', 'Audi'];
const arr = Array.from(cars, _ => "hi");
console.log(arr);

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!