在typescript中创建动态数组?

时间:2018-03-14 02:05:50

标签: javascript arrays angular typescript

我下面有一个数组。

let arr = [{_firstName: "john", _lastName: "tom", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19173432970", _sport: "Soccer"},
           {_firstName: "Jason", _lastName: "Deli", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19134592970", _sport: "Soccer"},
           {_firstName: "Shey", _lastName: "Ford", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+191767542970", _sport: "Soccer"},
           {_firstName: "Jake", _lastName: "Hoss", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+191723422970", _sport: "Soccer"},
           {_firstName: "Vamsee", _lastName: "Karru", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+18767692970", _sport: "Soccer"}];

我想比较数组中的所有对象并找到类似的obj,将它放在另一个数组中。

示例:

让我们看看上面数组中的前3个对象。它们都是相似的,因为它们具有相同的选择日期,插槽和运动。如果比较时所有这三个都相似,我想创建一个动态数组。最后,我可以获得不同数组中的所有相似数组对象。

数组的最后两个对象与前三个对象不同,因为它们具有不同的日期(selectedDate)。以下是我需要动态数组的方法。

arr1 = [{_firstName: "john", _lastName: "tom", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19173432970", _sport: "Soccer"},
        {_firstName: "Jason", _lastName: "Deli", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19145692970", _sport: "Soccer"},
        {_firstName: "Shey", _lastName: "Ford", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177612370", _sport: "Soccer"}];

arr2 = [{_firstName: "Jake", _lastName: "Hoss", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+191776639270", _sport: "Soccer"},
        {_firstName: "Vamsee", _lastName: "Karru", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+19100692465", _sport: "Soccer"}];

有什么方法可以通过创建动态数组来实现这一目标吗?

请帮忙。谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用功能reduce并按这些键分组。



let arr = [{_firstName: "john", _lastName: "tom", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19173432970", _sport: "Soccer"},           {_firstName: "Jason", _lastName: "Deli", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"},           {_firstName: "Shey", _lastName: "Ford", _selectedDate: "03/12/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"},           {_firstName: "Jake", _lastName: "Hoss", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"},           {_firstName: "Vamsee", _lastName: "Karru", _selectedDate: "03/13/2018", _slot: "6AM to 8AM", _phoneNumber: "+19177692970", _sport: "Soccer"}];
           
let result = arr.reduce((a, c) => {
  let groupKey = ['_selectedDate', '_slot', '_sport'].map(g => c[g]).join('|');
  (a[groupKey] || (a[groupKey] = [])).push(c);  
  return a;
}, {});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }