用数组连接2个对象并删除重复项(js)

时间:2017-08-24 12:34:59

标签: javascript arrays concat

有2个数组:看起来像这样

1)第一个数组

{day:mo, hours:[{id:1,color:grey},{id:2,color:grey},{id:3,color:grey},{id:4,color:grey}]}

2)第二个数组

{day:mo, hours:[{id:1,color:white},{id:2,color:white},{id:3,color:white},{id:4,color:white},{id:5,color:white}]}

结果必须是

{day:mo, hours:[{id:1,color:grey},{id:2,color:grey},{id:3,color:grey},{id:4,color:grey},{id:5,color:white}]}

所以我需要从2个数组中删除与第一个相同的值,然后将其连接起来。

尝试做点什么

clearArrFunc(arr1,arr2) {
    // do something
     for(var i in arr1){
     console.log(arr1[i]);
      for(var j in arr2)   {
        if(JSON.stringify(arr1[i].day) == JSON.stringify(arr2[j].day)) {
         delete arr2[j] ;
      }

       }

    }
  //  console.log(arr2);
    return arr1.concat(arr2);

    }

3 个答案:

答案 0 :(得分:2)

Concat两个数组然后从结果中消除重复的id:



a = [{id:1,color:'grey'},{id:2,color:'grey'},{id:3,color:'grey'},{id:4,color:'grey'}]
b = [{id:1,color:'white'},{id:2,color:'white'},{id:3,color:'white'},{id:4,color:'white'},{id:5,color:'white'}]

result = a
    .concat(b)
    .filter((x, i, self) => self.findIndex(y => y.id === x.id) === i);

console.log(result)




一个不太简洁但更有效的选择是从第一个数组构建一组id,然后只追加第二个元素,其中id不在集合中:



a = [{id:1,color:'grey'},{id:2,color:'grey'},{id:3,color:'grey'},{id:4,color:'grey'}]
b = [{id:1,color:'white'},{id:2,color:'white'},{id:3,color:'white'},{id:4,color:'white'},{id:5,color:'white'}]

ids = new Set(a.map(x => x.id))
result = a.concat(b.filter(x => !ids.has(x.id)))

console.log(result)




答案 1 :(得分:0)

另一种方法,从1st中出现的第二个数组中删除这些值,并将结果与​​第一个数组连接。

var x = [{id:1,color:'grey'},{id:2,color:'grey'},{id:3,color:'grey'},{id:4,color:'grey'}];
var y = [{id:1,color:'white'},{id:2,color:'white'},{id:3,color:'white'},{id:4,color:'white'},{id:5,color:'white'}];

var r = x.concat(y.filter(function(obj) {
    return !x.some(function(o) {
        return o.id===obj.id;
    });
}));

console.log(r);

答案 2 :(得分:0)

使用Lodash(https://lodash.com

const _ = require('lodash');

const a = [{id: 1, color: "grey"},{id: 2, color: "grey"},{id: 3, color: "grey"},{id: 4, color: "grey"}];
const b = [{id: 1, color: "white"},{id: 2, color: "white"},{id: 3, color: "white"},{id: 4, color: "white"},{id: 5, color: "white" }];

const result = _.unionBy(o1.hours, o2.hours), 'id');
// result = [{id: 1, color: "grey"}, {id: 2, color: "grey"}, {id: 3, color: "grey"}, {id: 4, color: "grey"}, {id: 5, color: "white"}]