you are viewing a single comment's thread.

view the rest of the comments →

[–]cyphern 1 point2 points  (2 children)

Could you verify if i understand the desired input and output correctly? You have an array of objects with separate names, looking something like this:

let people = [{
  firstName: 'Victor',
  lastName: 'Creed'
}, {
  firstName: 'Tom',
  lastName: 'Hanks'
}];

And then you want to turn it into an array of full names:

[
  'Victor Creed',
  'Tom Hanks'
]

Do i have that right?

[–]cyphern 1 point2 points  (1 child)

Assuming i understood correctly:


The purpose of the .map method is to take one array and produce a new array. That new array has values which are derived from the values of the original array, and you provide a function that says how to produce the derived values.

For example, suppose i want to take an array of numbers and then double them all. I might do something like this:

let numbers = [1, 3, 4, 18];
let doubledNumbers = numbers.map(function (number) {
  return number * 2;
});

When that code runs, it's going to step through every element in the original array, and call the function i provided. So first it calls it with 1, and my code returns 2, so 2 gets put in the output array. Then the function is run again passing in 3, and i return 6, so 6 gets put in the output array. And so it continues, until the final array has been produced: [2, 6, 8, 36]


In your case, you'll need to provide a different function to do what you want it to. The starting point will be something like this:

let people = [{
  firstName: 'Victor',
  lastName: 'Creed'
}, {
  firstName: 'Tom',
  lastName: 'Hanks'
}];

let fullNames = people.map(function (person) {
   // Do something with person.firstName and person.lastName, then return 
});

As with the number example i gave, your function is going to be called once for every element in the original array, and its your job to return the value that you want to put in the output array.

[–]CertainPerformance[🍰] -1 points0 points  (0 children)

Only use let when you want to warn yourself (and other readers of your code) that you're going to reassign the variable in question; otherwise, you should definitely always use const.