另一个javascript数组挑战

时间:2011-01-24 05:23:53

标签: javascript jquery arrays

解决另一个数组操作,我需要比平时更长的时间来解决这个问题。我需要帮助组合数组值:

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

这样最终的数组是:

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

为了清楚我是如何到达final_array的,alpha,bravo和delta只得到了他们的“|”替换为“ - ”,因为在我的array2模板上找不到它们。 charlie和echo得到了模板,因此基于array1替换了{}的相应值。老实说,Array1不是最好的关键:我现在可以提出的价值关系。

以下是一些要求L:

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

我已经阅读了关于jquery .map()并认为使用它可以实现,也许与Regexp一起使用。希望你能利用这些。此外,如果有帮助,final_array可以是任何顺序。

我真的需要了解这两个主题......:

提前谢谢。

2 个答案:

答案 0 :(得分:2)

修改:更新以匹配您的输出并评论一些疯狂。考虑到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"]

答案 1 :(得分:1)

虽然我做了一些假设,但设法获得了你想要的输出:

  • 带有{}括号的array1中的任何内容都不是模板化的。
  • array2中的关键字在array1中始终具有匹配值(这可以很容易地更改,但不确定您的规则是什么)。

代码:

// 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;
}