Tell Me Why I'm Wrong: DNA Pairing Solution

I created a solution to the DNA Pairing Challenge but I’m not sure why map works here.

function pairElement(str) {
  let paired = [];
  str = str
  .split("")
//how does map work here?
  .map(letter => {
    return letter == "A" ? paired.push(["A", "T"])
    : letter == "T" ? paired.push(["T", "A"])
    : letter == "G" ? paired.push(["G", "C"])
    : letter == "C" ? paired.push(["C", "G"])
    : letter;
  });
  return paired;
}

pairElement("GCG");

I’ve come to the conclusion that I’m basically using map incorrectly and I should instead be using forEach. Instead of returning an array the way map is built, I’m forcing it to push a nested array to the paired variable.

Any thoughts or input would be appreciated.

Use can use map like a forEach but it is an anti-pattern. However, it will still work.

2 Likes

map is intended to replace values in an array. Your function should return the value that you want the element to be replaced with. For example, if letter is “A”, you could replace it with ["A", "T"].

1 Like

Right! I thought I tried it but I must have made an error because I thought it didn’t work. This is how map should have been used:

function pairElement(str) {
  let paired = [];
  return str
  .split("")
  .map(letter => {
    return letter == "A" ? ["A", "T"]
    : letter == "T" ? ["T", "A"]
    : letter == "G" ? ["G", "C"]
    : letter == "C" ? ["C", "G"]
    : letter;
  });
}

pairElement("GCG");

Thanks for educating me on anti-patterns. That makes sense :slight_smile: