When looping through an array I wish to push the elements to a new array. That array however remains empty

Issue

When I run this loop it takes in an array which contains eight numbers, it loops through and simply pushes them to a global array which is named results. For some reason when I console.log this array outside of the loop it returns 0 []. I wish it to return the eight numbers from the other array.

const results = []

const validate = arr => {
  for(let i = 0; i < arr.length; i++){
    results.push(arr[i])
  }

}
console.log(results)

Solution

Your code would work if you included the original array of numbers and you call the function that iterates over it:

let arr = [1,2,3,4,5,6,7,8];
let results = [];

function validate() {
  for(let i = 0; i < arr.length; i++){
    results.push(arr[i])
  }
}

validate();
console.log(results)

But, the Array.prototype.map() method was designed to do just this type of thing:

let arr = [2,4,6,8];

let results = arr.map(function(element){
  return element; // Returns item to resulting array
});

console.log(results)

Answered By – Scott Marcus

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published