0

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([]));

3
  • Hi Ulfa, when you only get the last iteration of an array in an object it is likely you have either overwritten the previous items in the object rather than appending to the object or you are creating a new object each time. Commented Sep 21, 2019 at 14:41
  • Yes, it only returns the one object you created - person - with the values you assigned to it last. What do you actually want to do, return multiple objects in an array? Commented Sep 21, 2019 at 14:42
  • 1
    @nithin Provide that as an answer instead of big code blob in comment Commented Sep 21, 2019 at 14:45

3 Answers 3

1

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']]));

Sign up to request clarification or add additional context in comments.

2 Comments

it mustn't use any built in function such as map, how about only use for loop?
I added an example with a for loop.
0

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]
};

});

1 Comment

it mustn't use any built in function such as map or anything
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.