1

Hey I'm pretty new to coding. I've tried looking around for how to do this but am at a loss.

Below are the two functions, which are in an object.

listPeople: function () {
    let array = []
    return array;
    // returns an array of all people for whom tasks exist
},
add: function ( name, task ) {
    return this.listPeople().push( name )
},

If I run this, the add function returns 1. and will return 2 if I push two things in, and so on. What's going on here, how do i push the name variable from add into the array in listpeople?? The name variable is 'zeke' by the way.

Sorry in advance if this doesn't make sense :D

3
  • if this doesn't make sense very true, It doesn't make sense... Please be clear and specific what exactly do you want and You should add minimal reproducible code, so that people can understand your problem clearly. Commented Sep 29, 2021 at 4:30
  • What you are trying to do? Commented Sep 29, 2021 at 4:32
  • 1
    Every time you call listPeople, you’re creating a new array, which then goes nowhere because it isn’t saved anywhere. Commented Sep 29, 2021 at 4:40

2 Answers 2

4

It should probably look more like this. Create an arr property, and push objects into it from add. You can then return that list from listPeople.

const obj = {
  arr: [],
  listPeople: function() {
    return this.arr;
  },
  add: function(name, task) {
    return this.arr.push({ [name]: task });
  }
}

obj.add('bob', 'Shopping');
obj.add('Betty', 'Singing');
console.log(obj.listPeople());

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

Comments

1

What's happening in your code is that the add function is returning the result of the .push() method (the new length of the array).

If your intent is to actually return the array, you should modify the add method as follows:

add: function ( name, task ) {
    var people = this.listPeople();
    people.push(name);
    return people;
},

Additionally, while changing listPeople to an array property instead of a method may work better on a shallow level, I don't know what you may have planned to implement into the listPeople method. And it may only confuse/complicate things as far as answering the question you have asked.

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.