合并数组并保持排序 [英] Merge arrays and keep ordering

查看:66
本文介绍了合并数组并保持排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已根据@Kaddath的良好建议对问题进行了编辑,以突出显示以下事实:排序不必是字母顺序的,而是取决于项在数组中的位置.

The question has been edited following the good advise from @Kaddath to highlight the fact that the ordering doesn't have to be alphabetical but depending on the position of items inside the arrays.

我有一个数组数组,其中每个数组都基于给定的顺序,但是它们可以有所不同.

I have an array of arrays where each of the arrays are based on a given ordering but they can differ a bit.

例如,基本顺序是 X->D->-B ,这是我的数组数组:

For example, the base ordering is X -> D -> H -> B and here is my array of arrays:

const arrays = [
  ['X', 'D', 'H', 'B'],
  ['X', 'D', 'K', 'Z', 'H', 'B', 'A'],
  ['X', 'M', 'D', 'H', 'B'],
  ['X', 'H', 'T'],
  ['X', 'D', 'H', 'B']
]

我想将所有数组合并为一个数组,并删除重复项,但要保持排序.在我的示例中,结果为 ['X','M','D','K','Z','H','T','B','A'] .

I would like to merge all arrays into a single one and remove duplicates but by keeping the ordering. In my example the result would be ['X', 'M', 'D', 'K', 'Z', 'H', 'T', 'B', 'A'].

在该示例中,我们可以看到 M 在第三个数组中的 X D 之间,并且它被放置在之间X D 在最终输出中.

In the example we can see that M is between X and D inside the third array and it is so placed between X and D in the final output.

我知道可能会发生冲突,但这是以下规则:

I know conflicts may arise but here are the following rules:

  • 每个项目都应出现在最终输出中.
  • 如果某项在多个数组中的不同位置出现,则第一个外观是右侧的外观(跳过其他外观).

到目前为止,我所做的是通过使用

What I've done so far is merging all of these arrays into a single one by using

const merged = [].concat.apply([], arrays);

(请参见 https://stackoverflow.com/a/10865042/3520621 ).

然后通过使用 https://stackoverflow.com/a/1584377/3520621:

Array.prototype.unique = function() {
    var a = this.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
}; 
const finalArray = merged.unique();

但是我的结果是这样的

[
  "X",
  "D",
  "H",
  "B",
  "K",
  "Z",
  "A",
  "M",
  "T"
]

欢迎任何帮助!

谢谢.

推荐答案

const arrays = [
  ['X', 'D', 'H', 'B'],
  ['X', 'D', 'K', 'Z', 'H', 'B', 'A'],
  ['X', 'M', 'D', 'H', 'B'],
  ['X', 'H', 'T'],
  ['X', 'D', 'H', 'B']
];
const result = [];
arrays.forEach(array => {
  array.forEach((item, idx) => {
    // check if the item has already been added, if not, try to add
    if(!~result.indexOf(item)) {
      // if item is not first item, find position of his left sibling in result array
      if(idx) {
        const result_idx = result.indexOf(array[idx - 1]);
        // add item after left sibling position
        result.splice(result_idx + 1, 0, item);
        return;
      }
      result.push(item);
    }
  });
});
console.log('expected result', ['X', 'M', 'D', 'K', 'Z', 'H', 'T', 'B', 'A'].join(','));
console.log(' current result',result.join(','));

这篇关于合并数组并保持排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆