How can I skip value in array using map or group elements in Array?
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
Solution 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
Solution 2:
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