.map() examples

Hi here some examples of the .map() method if you want to read more about this method please click here and enjoy 🙂

1.- In this code we will go through every position in the array (myData) and the map will return us every element into another array (myResult):

const myData = ["cristina", "efrain", "nayeli", "gonzalo", "carolina"];

const myResult = myData.map((name) => {
  return name;
});

console.log("myResult --->", myResult);

Result:

Ok, is not making sense return another array if we already have an array, correct? well, if instead of return an array again we can return an array of objects (if we need this format)

const myData = ["cristina", "efrain", "nayeli", "gonzalo", "carolina"];

const myResult = myData.map((name) => {
  return  { name };
});

console.log("myResult --->", myResult);

Result:

Nice, but wait we can do this with less code 🙂

Just delete the the pair of brackets, the return and the “;” and insert a pair of parenthesis (this means a return)

const myData = ["cristina", "efrain", "nayeli", "gonzalo", "carolina"];

const myResult = myData.map((name) => ({ name }));

console.log("myResult --->", myResult);

Result:

By Cristina Rojas.