简体   繁体   中英

When I access to a key, I want its value and set it in an array. The access is by using strings

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing When I access to a key, I want its value and set it array. The way I try to access is with a string. For example: GCG. Therefore, I want to get

[["G", "C"], ["C","G"],["G", "C"]]

How may I do that?

function pairElement(str) {
  let dna = {
         "A": "T",
         "C": "G",
         "T": "A",
         "G": "C"
     }
}

pairElement("GCG");

I think you'll want to:

1) Turn the incoming string into an array using split ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split )

2) Turn each element in that array into its array using map ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map ) and build the pair you're looking for.

Here you go

function pairElement(str) {
  let dna = {
         "A": "T",
         "C": "G",
         "T": "A",
         "G": "C"
     }

  let indi = str.split('');
  var dna_arr = [];
  for(var x=0; x<indi.length; x++) {

    var char = indi[x];
    dna_arr.push(char);
  }

  return dan_arr;



}

pairElement("GCG");

Although I'm not exactly sure on what you want to do, this does give the output you're expecting.

 function pairElement(str) { const dna = { "A": "T", "C": "G", "T": "A", "G": "C" } let arr = []; for (const key of str){ arr.push([key, dna[key]]) } return arr; } // some input tests console.log(pairElement("GCG")); console.log(pairElement("ACTG")); console.log(pairElement("CCGAT"));

Or a one liner:

 function pairElement(str) { const dna = { "A": "T", "C": "G", "T": "A", "G": "C" } return str.split('').map(key => [key, dna[key]]) } // some input tests console.log(pairElement("GCG")); console.log(pairElement("ACTG")); console.log(pairElement("CCGAT"));

Note that you can iterate through string in Javascript:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM