Home > Back-end >  When looping through an array I wish to push the elements to a new array. That array however remains
When looping through an array I wish to push the elements to a new array. That array however remains

Time:05-21

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)

CodePudding user response:

What you have done here is simply define a function that copies the contents of the array that has been passed into it. You need to call the function validate with the appropriate value.

const results = []

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

}
validate([1,2,3,4,5,6,7,8]);
console.log(results);

CodePudding user response:

That is because you have to run the function validate, now you are just printing results[] which has no items.

validate(arr);

const results = []
const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const validate = arr => {
  for (let i = 0; i < arr.length; i  ) {
    results.push(arr[i])
  }

}
validate(arr);
console.log(results);

But if you want to make a copy, you can just use:

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const results = [...arr];
console.log(results);

CodePudding user response:

You missed calling the function.

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const result = [];
arr.map((num) => result.push(num));
console.log(result);

CodePudding user response:

const results = []
const validate = (arr) => {
    console.log(arr)
    arr.forEach((value)=>{
        results.push(value)
    });
}

validate([1,2,3,4,5,6,7,8]);
console.log(results);

CodePudding user response:

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)

  • Related