JavaScript .map using multiple array sources

74 views Asked by At

I have a test that provides 4 values:

fPortTotal = a number with how many ports in a firewall test.

fProtocol = an array with what protocol the port is (ex. UDP, TCP)

fPorts = an array with what port number

fStatus = an array with open or closed depending on the port

in all the arrays [0] is the first port, [1] is the 2nd, and so on. I want to use the .map method to display each port's information in a <p>. The issue is I'm having a large amount of difficulty understanding the .map method and how to use it. I beleave the "skeleton" of the function should look like this:

function populateFw(fPorts, fStatus, fPortTotal, fProtocol) {
    var output = document.getElementById('firewallRes');
    var text = document.createElement ('p');
    text.id = 'firewallEndResults';
    text.innerHTML = arrayOfArrays.map;
}

any help would be appreciated.

3

There are 3 answers

5
Talmacel Marian Silviu On BEST ANSWER

You can try something like this:

function populateFw(fPorts, fStatus, fPortTotal, fProtocol) {
    var output = document.getElementById('firewallRes');
    fPorts.forEach((port, index) => {
       const text = document.createElement('p');
       text.innerText= `${port}: ${fProtocol[index]} - ${fStatus[index]}`;
       output.appendChild(text);
    })
}
6
Aleks On

ForEach would be better here. Map returns an object, you don't need that.

fStatus.forEach((_, index)=>{
  //then using index acces all the information
  const protocol = fProtocol[index];
  const protNumber = fPorts[index]
  ....
  text.innerHTML += 'Protocol is '+protocol+' and port number is '+protNumber;
});

Edit: also example of Talmacel Marian Silviu is basically the same thing.

1
Daniil Loban On

do it like this:

for(i=0; i<fPorts; i++){
  var text = document.createElement ('p');
  text.id = `firewallEndResults${i}`;
  text.innerHTML = `${fStatus[i]}, ${fPortTotal[i]}, ${fProtocol[i]}`;
  somediv.appendChild(text); // don't forget  
}

map is function for change array items and need callback

const newArray = arrayOfArrays.map(callback)

or

const newArray = arrayOfArrays.map((i)=>{ do something in cycle })

if you use React you can use map in JSX, but this is other story