0

I am trying to print a list of persons that share same address and company name My array:

persons = [
 { address: "Wallstreet",
  company: "ABC",
  name: "John",
  telephoneNr: "12345"
 },
 { address: "Wallstreet",
  company: "ABC",
  name: "Rick",
  telephoneNr: "12857"
 },
 { address: "Wallstreet",
  company: "ABC",
  name: "Eva",
  telephoneNr: "38665"
 }
]

I am using map function, but I want to print address and company name only once, since they all share same address and same company. How can I skip printing addresses and company name for the second, third and n time in the loop?

{persons.map((item, index) => {
  return (
    <p>
      {item.address}
    </p>
    <p>
      {item.company}
    </p>
    <p>
      {item.name}: {item.telephoneNr}
    </p>
)})}

My print looks like this:

Wallstreet
ABC
John:12345
Wallstreet
ABC
Rick:12857
Wallstreet
ABC
Eva: 38665

And I want my print to look like this:

Wallstreet
ABC
John:12345
Rick:12857
Eva: 38665

2 Answers 2

1

Please update this code:

{persons.map((item, index) => {
              return (
                if (index === 0) {
                   <p>
                    {item.address}
                   </p>
                   <p>
                    {item.company}
                   </p>
                   <p>
                    {item.name}: {item.telephoneNr}
                   </p>
               } else { 
                   <p>
                    {item.name}: {item.telephoneNr}
                   </p>
               }
              )})}

Your output will be look like this:

 Wallstreet
 ABC
 John:12345
 Rick:12857
 Eva: 38665
Sign up to request clarification or add additional context in comments.

1 Comment

It will work only if the address and company are in index 0
1

You can use Map object Map object

const map = new Map()
map.set([address, company].toString(), [{name, telephoneNr}])

then you need to get the value and set it with the new item and if the key is the same it will map to the same key-value pair and after that, you can iterate the map object and to print 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.