0

I want to concatenate 2 lists in immutable.js.

Both lists have this structure: { id, value }

The algorithm concatenate should do this:

  • If an ID exists in both list1 and list2 take the value from list2.
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' },
]

If Immutable.js has this functionality with another type (eg. Dictionary), I could also use that.

4

1 回答 1

1

联合算法

首先,您必须维护两个带有 key asid和 value as的映射,object然后检查更大尺寸的数组的长度,并将具有小尺寸映射的更大尺寸的数组传递给在merged那里运行,您可以迭代数组并检查它是否存在于如果是映射,则更新对象并从映射中删除该行,否则将对象添加到输出中。在 for 循环完成后检查 map 是否存在元素,然后将 map 中的所有值推入输出数组并返回;

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/

于 2018-11-10T14:06:37.673 回答