ulfa
ulfa

Reputation: 17

Why this javascript function not returning multiple objects from for loop?

I want to create a function that returns multiple objects from array, but it only returns an object from index[1]. Is there a mistake in this for loop? I tried to put the return inside the loop, it returns only one object too.

function Me(arr) {
  var person = {}
  var year = new Date().getFullYear()
  for (var i = 0; i < arr.length; i++) {
    console.log(i + 1 + ". " + arr[i][0] + " " + arr[i][1] + " :")
    person["firstName"] = arr[i][0]
    person["lastName"] = arr[i][1]
    person["gender"] = arr[i][2]
    person["age"] = arr[i][3]
    if (arr[i][3] === undefined) {
      person.age = "Invalid Birth Year"
    } else {
      person.age = year
    }
  }
  return person;
}

console.log(Me([
  ['Christ', 'Evans', 'Male', 1982],
  ['Robert', 'Downey', 'Male']
]));
// 1. Christ Evans:
// { firstName: 'Christ',
//   lastName: 'Evans',
//   gender: 'Male',
//   age: 37 }
// 2. Robert Downey:
// { firstName: 'Robert',
//   lastName: 'Downey',
//   gender: 'Male',
//   age: 'Invalid Birth Year' }
console.log(Me([]));

Upvotes: 0

Views: 88

Answers (3)

Abhishek-Saini
Abhishek-Saini

Reputation: 743

function Me(arr) {
    var person = {}
    // this person variable is used to store the person information generated in each iteration by our for loop

    let personList = [] 
    // personList variable store the data of each person

    var year = new Date().getFullYear()
    for (var i = 0; i < arr.length; i++) {        
        console.log(i + 1 + ". " + arr[i][0] + " " + arr[i][1] + " :")
        person["firstName"] = arr[i][0]
        person["lastName"] = arr[i][1]
        person["gender"] = arr[i][2]
        person["age"] = arr[i][3]
        if (arr[i][3] === undefined) {
        person.age = "Invalid Birth Year"
        } else {
        person.age = year
        }

        personList.push({...person});
        // as for each iterator our loop generate a person now we have to push that person in personList

        // {...person} this is the spread operator syntax to this helps us to make a copy of person object and push that copy in personList.

    }
    return personList;
    // finally returing the personList having persons data
}

console.log(Me([
    ['Christ', 'Evans', 'Male', 1982],
    ['Robert', 'Downey', 'Male']
]));

The above code can solve your problem.

Note: we use spread operator to generate a new copy of our original person object and push that new object in personList, we didn't use the same person reference to push in personList because at each iteration that person object properties get change and effect our personList and thus effect our result.

Upvotes: 0

some
some

Reputation: 49632

To answer your question, why you only get one object, let us look at your code:

function Me(arr) {
  var person = {}
  // for-loop removed
  return person;
}

You only return one object. And it will have the data of the last iteration of your loop.

Another thing with your for-loop:

for (var i = 0; i < arr.length; i++) {
  person["firstName"] = arr[i][0]
  person["lastName"] = arr[i][1]
  // more code removed
}

You can do a for loop like that, but there are better ways. Notice how you use arr[i] every time you access the object? That is very inefficient. One way to make the code much more readable is to get the value at the top of the loop: let item = arr[i]; But there are even better ways to iterate over an array. There are ´forEach, but in this casemap` is better, since it looks like you want to map the values in the array to a new array, with an object with the data from the first array.

I'm using Array.prototype.map to iterate over the array.

"use strict";
function Me(arr) {
  let currentYear = new Date().getFullYear();
  return arr.map( item => ({
    firstName : item[0],
    lastName : item[1],
    gender: item[2],
    age : item[3] === undefined ? "Invalid Birth Year" : currentYear - item[3]
  }) )
}

console.log(Me([['Christ', 'Evans', 'Male', 1982], ['Robert', 'Downey', 'Male']]));

If you aren't allowed to use map, but have to use a for-loop, you can do it like this:

"use strict";
function Me(arr) {
  var output = []; // starts with an empty array
  var currentYear = new Date().getFullYear();
  
  for ( var i = 0; i < arr.length; i+=1 ) {
    var item = arr[i];
    output.push({
      firstName : item[0],
      lastName : item[1],
      gender: item[2],
      age : item[3] === undefined ? "Invalid Birth Year" : currentYear - item[3]
    })
  }
  
  return output;
}

console.log(Me([['Christ', 'Evans', 'Male', 1982], ['Robert', 'Downey', 'Male']]));

Upvotes: 1

Nithin Thampi
Nithin Thampi

Reputation: 3689

Why not use something simpler like

const returnVal = [["Christ", "Evans", "Male", 1982], ["Robert", "Downey", "Male"]].map(person => {
return {
  firstName: person[0],
  lastName: person[1],
  gender: person[2],
  age: person[3] === undefined ? "Invalid Birth Year": person[3]
};

});

Upvotes: 0

Related Questions