简体   繁体   English

如何将两个集合变成一个

[英]How to transform two collections into one

This is as much a basic data structure question as it is a specific implementation question. 这既是一个基本的数据结构问题,又是一个特定的实现问题。

I have two collections: 我有两个收藏:

['One', 'Two', 'Three']
[{'Name': 'Two', 'Time': '12:00'}, {'Name': 'Four', 'Time': '14:30'}]

What I want is to merge them into a third collection: 我想要将它们合并到第三个集合中:

[
    {'Name': 'One', 'HasTime': false, 'Valid': true },
    {'Name': 'Two', 'HasTime': true, 'Valid': true, 'Time': '12:00' },
    {'Name': 'Three', 'HasTime': false, 'Valid': true },
    {'Name': 'Four', 'HasTime': true, 'Valid': false, 'Time': '14:30' },
]

I can do this like in this pseudo-code: 我可以像下面的伪代码那样执行此操作:

// Pseudo-Code, hence no isOwnProperty and other checks
var r = [];
for(v in one) {
  var obj = { Name: v, Valid: true, HasTime: false };
  for(t in two) {
    if(t.Name === v) {
        obj.HasTime = true;
        obj.Time = t.Time;
        break;
    }
  }
  r.push(obj);
}

for(t in two) {
    var valid = false;
    for(x in r) {
        if(x.Name === t.Name) {
           valid = true;
           break;
        }
    }
    if(!valid) {
      var obj = new { Name: t.name, Valid: false, HasTime: true, Time: t.Time };
      r.push(obj);
    }
}
return obj;

This seems inefficient and I wonder if Angular even already has such a function - my problem is that I don't know what this technique is called. 这似乎效率低下,我想知道Angular是否已经具有这样的功能-我的问题是我不知道这种技术叫什么。 I guess there is a term in Set theory or functional programming, as this is essentially a Union followed by a transform, but the basic term for this in functional programming eludes me - is there a name for this? 我猜想集合论或函数式编程中有一个术语,因为这本质上是一个联合,后面是一个转换,但是函数式编程中的基本术语使我难以理解-对此有名称吗?

You could call that a map-reduce if you want, as you basically need first to transform both arrays to a unified structure ( Map ), and then merge them together ( Reduce ). 您可以根据需要将其称为map-reduce ,因为基本上您首先需要将两个数组都转换为统一结构( Map ),然后它们合并在一起( Reduce )。

However there is nothing magic in it, especially since your structure is totally custom, so you cannot avoid your aglorithm. 但是,其中没有什么魔术,尤其是由于您的结构完全是自定义的,因此您无法避免自己的算法。

You don't really need map-reducing since you only have two arrays, but to give you an idea it would look like this: 因为只有两个数组,所以您实际上并不需要减少映射,但是给您一个想法,它看起来像这样:

var result = [one, two].map(function(arr) {
  // transform arr into {Name, Valid, HasTime} items
}).reduce(function(arr1, arr2) {
  // merge arr1 and arr2
});

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

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