1

I'm still a newbie with javascript. I'm facing a problem with mapping an array. I don't know how to return the an array with objects.

This is the initial array:

array1 = [{firstName: "Harry"},
          {lastName: "Potter"}];

When i do array1.map, it returns:

array1 = ["Potter"];

I want to make array1 to be like this after mapping the lastName:

array1 = [{lastName: "Potter"}];
3
  • 1
    When i do array1.map, it returns: I can't think of any .map callback that would result in that Commented Dec 30, 2019 at 6:09
  • why does your array look like that in the first place? why not just have both the firstName and lastName keys on one object? Commented Dec 30, 2019 at 6:12
  • Its okay guys. I just solved it by deleting the firstName property for every loop. Commented Dec 30, 2019 at 6:17

2 Answers 2

2

You can use filter function instead

array1 = [{firstName: "Harry"},
          {lastName: "Potter"}];
          
console.log(array1.filter(x => x.lastName === "Potter"));

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

Comments

0

As per the docs:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

It creates new array and returns it.

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.