Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Trying to push a string into an array returned from another function

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!