Home > database >  push 5 string from array to new new Array using javascript/ node js
push 5 string from array to new new Array using javascript/ node js

Time:03-29

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

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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

  • Related