简体   繁体   English

另一个JavaScript数组挑战

[英]Another javascript array challenge

Solving another array manipulation, and I'm taking longer than usual to solve this. 解决了另一种数组操作,我花了比平时更长的时间来解决这个问题。 I need help in combining array values: 我需要组合数组值的帮助:

var array1 = ["alpha|LJ", "bravo|MH", "charlie|MH", "delta|MF",
              "echo|16", "{foxtrot}|GG", "{golf}|HS"];

var array2 = ["charlie-{golf}-{foxtrot}", "echo-{golf}"]; //some templates

such that the final array be: 这样最终数组为:

final_array = ["alpha-LJ", "bravo-MH", "charlie-HS-GG-MH", "delta-MF",
               "echo-HS-16"];

To make it clear how I arrived with the final_array, alpha, bravo and delta only got their "|" 为了明确说明我是如何使用final_array到达的,alpha,bravo和delta只得到了它们的“ |” replaced with "-" since they are not found on my array2 template. 因为在我的array2模板上找不到它们,所以用“-”代替。 charlie and echo got the template so the respective values of the {} were replaced based on array1. charlie和echo得到了模板,因此根据array1替换了{}的各个值。 Array1 honestly is not the best key:value relationship that I could come up for now. 老实说,Array1并不是我现在能想到的最好的key:value关系。

Here are some requirementL: 以下是一些要求:

* Anything in array1 with {} braces are not meant to be templated.
* Keywords in array2 will always have a matching value in array1. 

I've read about jquery .map() and thinking that it is achievable using this, maybe together with Regexp. 我已经读过有关jquery .map()的文章,并认为使用它可以实现,也许可以与Regexp一起使用。 Hope you'll utilize these. 希望您会利用这些。 Also, if it helps, final_array can be of any order. 同样,如果有帮助,final_array可以是任何顺序。

I really need to up my knowledge on these two topics... :| 我真的需要加强对这两个主题的了解...:|

Thank you in advance. 先感谢您。

Edit : Updated to match your output and comment some of the madness. 编辑 :更新以匹配您的输出并评论一些疯狂。 This doesn't feel like it's the most efficient, given the split() done to values at the start and then again at the end...but it works. 考虑到split()在开始时先对值进行了设置,然后在结束时又对值进行了设置,这似乎并不是最有效的方法……但它确实有效。

function funkyTransform( values, templates ){
  // Make a copy of the array we were given so we can mutate it
  // without rudely changing something passed to our function.
  var result = values.concat();

  // Map {value} entries for later lookup, and throw them out of the result
  var valueMap = {};
  for (var i=result.length-1;i>=0;--i){
    var pair = result[i].split('|');
    if (pair[0][0]=="{"){
      valueMap[pair[0]] = pair[1];
      result.splice(i,1); // Yank this from the result
    }
  }
  console.log(valueMap);
  // {
  //   "{foxtrot}": "GG",
  //   "{golf}":    "HS"
  // }

  // Use the value map to replace text in our "templates", and
  // create a map from the first part of the template to the rest.
  // THIS SHOULD REALLY SCAN THE TEMPLATE FOR "{...}" PIECES
  // AND LOOK THEM UP IN THE MAP; OOPS O(N^2)
  var templateMap = {};
  for (var i=templates.length-1;i>=0;--i){
    var template = templates[i];
    for (var name in valueMap){
      if (valueMap.hasOwnProperty(name)){
        template = template.replace(name,valueMap[name]);
      }
    }
    var templateName = template.split('-')[0];
    templateMap[ templateName ] = template.slice(templateName.length+1);
  }
  console.log(templateMap);
  // {
  //   "charlie": "HS-GG",
  //   "echo":    "HS"
  // }

  // Go through the results again, replacing template text from the templateMap
  for (var i=result.length-1;i>=0;--i){
    var pieces = result[i].split('|');
    var template = templateMap[pieces[0]];
    if (template) pieces.splice(1,0,template);
    result[i] = pieces.join('-');
  }
  return result;
}

var output = funkyTransform( array1, array2 );
console.log(output);
// ["alpha-LJ", "bravo-MH", "charlie-HS-GG-MH", "delta-MF", "echo-HS-16"]

This managed to get your desired output, though I made a few assumptions: 尽管我作了一些假设,但这设法获得了所需的输出:

  • Anything in array1 with {} braces are not meant to be templated. array1中带有{}大括号的所有内容均不应作为模板。
  • Keywords in array2 will always have a matching value in array1 (this can easily be changed, but not sure what your rule would be). array2中的关键字在array1中将始终具有匹配值(可以轻松更改,但不确定您的规则是什么)。

Code: 码:

// This is the main code
var final_array = $.map(array1, function (item) {
    var components = item.split('|');
    // Ignore elements between {} braces
    if (/^\{.*\}$/.test(components[0])) return;
    components[0] = template(components[0]); 
    return components.join('-');
});

// Helper to lookup array2 for a particular string and template it
// with the values from array1
function template(str) {
    var index = indexOfMatching(array2, str, '-');
    if (index == -1) return str;

    var components = array2[index].split('-');
    var result = [str];
    for (var i = 1; i < components.length; i++) {
        result.push(array1[indexOfMatching(array1, components[i], '|')]
            .split('|')[1]);
    }
    return result.join('-');
}

// Helper to for looking up array1 and array2
function indexOfMatching(array, target, separator) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].split(separator)[0] === target) return i;
    }
    return -1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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