John Patrick John Patrick - 1 year ago 56
Javascript Question

In JavaScript, given an input string, create a function that returns an array containing an n number of 2d arrays

I'm trying to get the

output at the bottom of the sample code. Currently, my code is returning
. I would like to know which part I did wrong.

I would also like to know if there are other, more efficient approaches in solving the problem.

function pairElement(str) {

return str.split('')
return element.split('').map(function(pair){
if (pair == "G") {return ["G","C"];}
else if (pair == "C") {return ["C","G"];}
else if (pair == "T") {return ["T","A"];}
else {return ["A","T"];}

// -> Should be [["A","T"], ["T","A"], ["C","G"], ["G","C"]]
// -> But currently, it is returning undefined

Answer Source

You don't need to do .split twice. Here's a possible solution:

function pairElement(input){
    var pairs = { A: "T", T: "A", C: "G", G: "C" };
    return input.split("").map(char => [char, pairs[char]]);  // ES6 arrow function



"ATCG".split("") turns the string into an array ["A", "T", "C", "G"]. Then by applying a mapping function we can transform the output, character by character, into predefined pairs [["A","T"], ["T","A"], ["C","G"], ["G","C"]].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download