0

这可能会有点令人困惑,我不确定它是否可能,但我会很感激任何帮助。我有以下数组(列表的项目和数量可能会改变,这只是一个例子):

var list_1 = ["A - 2" , "E - 5" , "C - 7"];
var list_2 = ["D - 2" , "A - 2" , "E - 3"];
var list_3 = ["C - 1" , "E - 8" , "A - 7"];

我的预期输出是:

var final = ["A - 2" , "C - 1" , "D - 2" , "E - 3"];

我正在尝试做的事情:

我试图弄清楚如何遍历每个数组项,查看项开头的字母是否存在于前一个数组中,如果该项中的数字低于前一项,则将其替换为'final ' 列表。

任何想法,或者这是不可能的?

jQuery 是可以接受的

4

5 回答 5

2
var list_1 = ["A - 2" , "E - 5" , "C - 7"];
var list_2 = ["D - 2" , "A - 2" , "E - 3"];
var list_3 = ["C - 1" , "E - 8" , "A - 7"];

首先,合并列表(第三个 + 第二个 + 第一个):

var list = list_3.concat(list_2).concat(list_1);

创建一个地图,您将在其中放置每个字母的最小数字:

var final_map = {};

遍历所有项目,将每个项目拆分为字母 ( parts[0]) 和数字 ( parts[1])。

您将获得给定字母的当前最低数字。如果没有数字或新数字低于当前最低的数字,则更新地图。

list.forEach(function (item) {
  var parts = item.split(' - ');
  var current = final_map[parts[0]];

  if (!current || parts[1] < current) {
    final_map[parts[0]] = parts[1];
  }
});

最后,将地图转换为数组。

var final = [];
Object.keys(final_map).sort().forEach(function (key) {
  final.push(key + ' - ' + final_map[key]);
});
于 2012-06-12T19:56:46.867 回答
0

Well, you've pretty much answered your question yourself. All you need now is to change human-readable algorithm to JavaScript. Iterate over lists with for up to .length elements, use String.substring or regexp to split data and save maximum found number in an object, where letter will be key and number - the value. Then just create final array from this object in yet another for loop and sort it, specifying custom function.

于 2012-06-12T19:51:57.953 回答
0

I would just create a hash table that the key will be the integer while the value will just be a list of the letters. Than when it is time for you to print it you just go through the key + value as long as the value is not used before. You can also write your own sort function that really will look at the number first

于 2012-06-12T19:52:53.140 回答
0

您必须手动遍历数组:

var final = [];
$.each(list_1, function(i) { 
  // get each of your elements at index i. Ex list_1[i]
  // do the comparison, and push them to an final
  // possibly split the current element to match the letter and number
})
于 2012-06-12T19:50:53.017 回答
0

我会使用查找来保存当前值并遍历数组。

重新排列您的列表,

var lists = [["A - 2" , "E - 5" , "C - 7"], 
             ["D - 2" , "A - 2" , "E - 3"], 
             ["C - 1" , "E - 8" , "A - 7"]];

使用这个,

var f = {}; 
for (var i = 0; i < lists.length; i++) { 
  for (var j = 0; j < lists[i].length; j++) { 
    var s = lists[i][j].split(' - '); 
    var ex = f[s[0]]; 
    if (!ex || ex > s[1]) 
      f[s[0]] = s[1];
  } 
}; 
var a = [];
for (var obj in f) {
  if (f.hasOwnProperty(obj)) { 
    a.push('' + obj + ' - ' + f[obj]);
  }
};

["A - 2", "E - 3", "C - 1", "D - 2"]
于 2012-06-12T19:54:07.057 回答