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

181
Views
push 5 string from array to new new Array using javascript/ node js

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];

for (const value of dataArray){
 let newArray=[];
 for(i=0;i<5;i++)
 {
  newArray.push(value);
 }
 
 console.log(newArray)
}

I am trying to push only 5 string from array but its not working as expectation as my expected output is like this

console.log(newArray);

["A1","A2","A3","A4","A5"]

I am trying to get first 5 string from dataArray and pushing them in newArray

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

0

slice method will do the job for you.

Eg: dataArray.slice(0, 5); - This will return the first 5 items from dataArray.

In your code you are iterating through the dataArray and each item in dataArray is pushed into newArray 5 times and printing it. Also in each iteration through the dataArray, the variable newArray is reinitialised.

about 4 years ago · Juan Pablo Isaza Report

0

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];
let newArr = dataArray.filter((str,index) => {
    if(index < 5){
  return str;
  }
})
console.log(newArr)

about 4 years ago · Juan Pablo Isaza Report

0

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];


 let newArray=[];
 for(i=0;i<5;i++)
 {
  newArray.push(dataArray[i]);
 }
 
 
console.log(newArray);

another way is .slice()

so you can do just this

let dataArray=["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];

 console.log(dataArray.slice(0,5))

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!