0

I am a very beginner with Javascript and I'm working on a question from my Mentor that I'm totally stuck on:

Create a function that accepts one parameter. This parameter will be an array of objects. Each object will have 1 property name. The function should return a new array that is populated with the name properties from the objects.

Example

namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);

//returns ['Tacos', 'Burritos', 'Enchiladas']

I do not know how to make a for loop that will iterate over any array put into the function parameters. I've only done ones that have defined arrays.

This is what I have:

function namesFunction(){
  var arr = [];
  for (i = 0; i < arr.length; i++){
    console.log(arr[i].name);
  }
}

namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);

Any help is appreciated! Thank you!

CRice
  • 29,968
  • 4
  • 57
  • 70
  • 3
    Hint#1: your `namesFunction` does not accept any arguments – zerkms May 07 '18 at 21:41
  • Is the property name guaranteed to always be `name`? If yes, this was a [question from two hours ago](https://stackoverflow.com/questions/50220691/convert-an-array-of-map-to-a-simple-array-with-map-keys-es6) – ASDFGerte May 07 '18 at 21:43
  • https://www.w3schools.com/js/js_function_parameters.asp – Lars May 07 '18 at 21:47
  • **Hint #2**: Arrays have a **[`.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)** method that iterates the array and returns a new array with whatever contents you want (as determined by a callback function you supply). – Scott Marcus May 07 '18 at 21:49

1 Answers1

1

You're writing a function that takes an array:

function mapObjectsToNames(array) {}

And you want it to return a new array:

function mapObjectsToNames(array) {
    var result = [];
    return result;
}

You're going to have to iterate over each element in the array:

function mapObjectsToNames(array) {
    var result = [];
    for (var i = 0; i < array.length; i += 1) {
    }
    return result;
}

You already were logging the name property from each element:

function mapObjectsToNames(array) {
    var result = [];
    for (var i = 0; i < array.length; i += 1) {
        console.log(array[i].name);
    }
    return result;
}

Now you'll want to add the name to the new list:

function mapObjectsToNames(array) {
    var result = [];
    for (var i = 0; i < array.length; i += 1) {
        result.push(array[i].name);
    }
    return result;
}
Sean
  • 1,279
  • 9
  • 17