简体   繁体   English

Javascript-比较两个数组并将缺少的项添加到第一个数组中

[英]Javascript - Compare two arrays and add missing items into first array

Lets say I have two arrays details1 and details2. 可以说我有两个数组details1和details2。 Below are contents of the array 以下是数组的内容

var details1 =[];
details1[0] = {'ActivityName' : 'Act1',
              'Status' : 'Done'};
details1[1] = {'ActivityName' : 'Act2',
              'Status' : 'InProgress'};
details1[2] = {'ActivityName' : 'Act5',
              'Status' : 'Done'};

var details2 =[];
details2[0] = {'ActivityName' : 'Act2',
              'Status' : 'Done'};
details2[1] = {'ActivityName' : 'Act3',
              'Status' : 'Done'};

I need to compare both the arrays and add missing items and update the status based on name in array details1. 我需要比较两个数组并添加缺少的项,并根据数组details1中的名称更新状态。 My output should be 我的输出应该是

var details1 =[];
details1[0] = {'ActivityName' : 'Act1',
              'Status' : 'Done'};
details1[1] = {'ActivityName' : 'Act2',
              'Status' : 'Done'};
details1[2] = {'ActivityName' : 'Act3',
              'Status' : 'Done'};
details1[3] = {'ActivityName' : 'Act5',
              'Status' : 'Done'};

What is the best way to achieve this? 实现此目标的最佳方法是什么?

Convert both arrays to objects, merge them, sort keys and extract values: 将两个数组都转换为对象,合并它们,对键进行排序并提取值:

 var details1 =[]; details1[0] = {'ActivityName' : 'Act1','Status' : 'Done1'}; details1[1] = {'ActivityName' : 'Act2','Status' : 'InProgress'}; details1[2] = {'ActivityName' : 'Act5','Status' : 'Done1'}; var details2 =[]; details2[0] = {'ActivityName' : 'Act2','Status' : 'Done2'}; details2[1] = {'ActivityName' : 'Act3','Status' : 'Done2'}; let toObject = (a, key) => a.reduce((o, x) => Object.assign(o, {[x[key]]: x}), {} ); let merge = Object.assign( toObject(details1, 'ActivityName'), toObject(details2, 'ActivityName') ); let result = Object.keys(merge).sort().map(k => merge[k]); console.log(result); 

You could use a hash table as reference to the items. 您可以使用哈希表作为对项目的引用。

 var details1 = [{ ActivityName: 'Act1', Status: 'Done' }, { ActivityName: 'Act2', Status: 'InProgress' }, { ActivityName: 'Act5', Status: 'Done' }], details2 = [{ ActivityName: 'Act2', Status: 'Done' }, { ActivityName: 'Act3', Status: 'Done' }], hash = Object.create(null); details1.forEach(function (a) { hash[a.ActivityName] = a; }); details2.forEach(function (a) { if (hash[a.ActivityName]) { hash[a.ActivityName].Status = a.Status; return; } details1.push(hash[a.ActivityName] = a); }); details1.sort(function (a, b) { return a.ActivityName.localeCompare(b.ActivityName); }); console.log(details1); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

var details1 = [];
details1[0] = {'ActivityName': 'Act1',
    'Status': 'Done'};
details1[1] = {'ActivityName': 'Act2',
    'Status': 'InProgress'};
details1[2] = {'ActivityName': 'Act5',
    'Status': 'Done'};

var details2 = [];
details2[0] = {'ActivityName': 'Act2',
    'Status': 'Done'};
details2[1] = {'ActivityName': 'Act3',
    'Status': 'Done'};

//Merge function
var __merge = function (arr1, arr2) {
    return arr1.concat(arr2).reduce(function (prev, current, index) {

        if (!(current.ActivityName in prev.keys)) {
            prev.keys[current.ActivityName] = index;
            prev.result.push(current);
        } else {
            prev.result[prev.keys[current.ActivityName]] = current;
        }

        return prev;
    }, {result: [], keys: {}}).result;
}; 

details1 = (__merge(details1, details2));

And that's the result : 结果就是:

[{ ActivityName="Act1",  Status="Done"}, { ActivityName="Act2",  Status="Done"}, { ActivityName="Act5",  Status="Done"}, { ActivityName="Act3",  Status="Done"}]

ES6+ solution using a Map . 使用Map的 ES6 +解决方案。

The gist is to go through the first array and add all items to a map with ActivityName as the key and the actual object as the value. 要点是要遍历第一个数组,并将所有项目添加到以ActivityName为键,而实际对象为值的地图中。 Then iterate through the second array and either merge with a value at an existing ActivityName key or add a new value. 然后遍历第二个数组,并与现有ActivityName键上的值合并或添加一个新值。

Lastly, sort the result. 最后,对结果进行排序。

Note: This solution doesn't alter the existing arrays 注意:此解决方案不会更改现有阵列

 const details1 = [{ 'ActivityName': 'Act1', 'Status': 'Done' }, { 'ActivityName': 'Act2', 'Status': 'InProgress' }, { 'ActivityName': 'Act5', 'Status': 'Done' }]; const details2 = [{ 'ActivityName': 'Act2', 'Status': 'Done' }, { 'ActivityName': 'Act3', 'Status': 'Done' }]; const { assign } = Object; const map = new Map(); const addToMap = (detail) => { const { ActivityName: name } = detail; if (map.has(name)) { // if detail already exists, // create a new object by merging the current detail and the new detail detail = assign({}, map.get(name), detail); } map.set(name, detail); }; // add first then second details to a map details1.concat(details2).forEach(addToMap); // sort the keys and map them to values const result = [...map.keys()] .sort() .map(key => map.get(key)); // show the new result (NOTE: old arrays are unchanged) console.log(result); 

暂无
暂无

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

相关问题 JavaScript 比较两个 arrays 并将在第二个数组中具有相同属性值的项目推送到第一个数组 - JavaScript compare two arrays and push items to the first array that have the same property value in the second array Javascript比较两个不同大小的数组,并返回不在第二个数组中的项目 - Javascript Compare two arrays with different sizes and return the items that are not in second array 比较两个对象的 arrays,如果缺少某个键的值,则将具有该值的 object 添加到数组中 - 两种方式 - Compare two arrays of objects and if value for a certain key is missing, add an object with that value to the array - two ways 比较两个数组并构建要删除的项目和要添加的项目的堆栈 - Compare two arrays and build a stack of items to remove and items to add 比较两个arrays的对象,判断第一个数组的日期是否在第二个数组Javascript的指定范围内 - Compare two arrays of objects and find out if the date from the first array is within the specified range in the second array in Javascript 推送到数组并比较两个数组的JavaScript - Push to array and compare two arrays JavaScript 数组和JavaScript-如何比较两个数组 - Array and javascript - how to compare two arrays 比较两个数组并将0添加到缺少的元素 - compare two array and add 0 to missing element 比较 JavaScript 中的两个 arrays 对象,如果为真,则将新项目保存到 MongoDB - compare two arrays of Objects in JavaScript and if true save new items to MongoDB 比较JavaScript中的两个数组 - Compare two arrays in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM