Immutable.js算法:List.update_or_add(项)

Immutable.js algorithm: List.update_or_add(item)

我想连接 immutable.js 中的 2 个列表。

两个列表都具有以下结构:{ id, value }

算法连接应该这样做:

let list1 = [
    { id: 1, value: 'foo' },
    { id: 3, value: 'bar' },
    { id: 2, value: 'baz' },
]

let list2 = [
    { id: 1, value: 'quux' }, // id 1 exists in list1
    { id: 4, value: 'asd' },
]

let result = [
    { id: 1, value: 'quux' }, // from list 2 
    { id: 3, value: 'bar' },
    { id: 2, value: 'baz' },
    { id: 4, value: 'asd' },
]

如果 Immutable.js 对另一种类型(例如字典)具有此功能,我也可以使用它。

联合算法

首先,您必须维护两个映射,键为 id,值为 object,然后检查较大尺寸的数组的长度,并将较大尺寸的数组和较小尺寸的映射传递给merged 函数在那里你可以迭代数组并检查它是否存在于地图中如果是然后更新对象并从地图中删除该行否则将对象添加到输出中。 for 循环完成后检查 map 是否存在元素然后将 map 中的所有值推送到输出数组和 return;

index.js

const old = [
  { id: 1, value: 'foo' },
  { id: 3, value: 'bar' },
  { id: 2, value: 'baz' },
];

const newa = [
    { id: 1, value: 'quux' }, // update
    { id: 4, value: 'asd' }, // push

];

 function merged(input,filterMap){
     var output = [];
      input.forEach(function(eachRow){
                        if(filterMap.hasOwnProperty(eachRow.id)){
                 output.push(Object.assign(eachRow,filterMap[eachRow.id]));
                 delete filterMap[eachRow.id];
              }else{
                  output.push(eachRow);
              }
                });

          if(Object.keys(filterMap).length > 0){
            output = output.concat(Object.values(filterMap));
          }
          return output;
 }

function parseData(first,second){
   var mapFirst = {},
       mapSecond = {};
   var output = [];
   first.forEach(function(eachRow){
            mapFirst[eachRow.id] = eachRow;
        });

   second.forEach(function(eachRow){
                    mapSecond[eachRow.id] = eachRow;
   });

   if(first.length > second.length){
        return merged(first,mapSecond);
   }else{
     return merged(second,mapFirst);
   }
}

console.log(parseData(old,newa));

工作 jsFiddle 演示 - https://jsfiddle.net/qz25hnmf/