【问题标题】:Remove Only One of Same Object from An Array从数组中仅删除一个相同对象
【发布时间】:2020-05-03 10:04:44
【问题描述】:
var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];

var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];

var filteredArray  = array.filter(function(array_el){
   return anotherOne.filter(function(anotherOne_el){
      return anotherOne_el.id == array_el.id;
   }).length == 0
});

此代码删除所有“id:2”对象。像这样做:

{id :1, name :"test1"},{id :3, name :"test3"}

但我只想删除同一个对象中的一个。像这样:

{id :1, name :"test1"},{id :2, name :"test2"},{id :3, name :"test3"}

但是如果另一个数组有两个相同的对象,则需要两个删除。

【问题讨论】:

  • 也分享你想要的结果..以获得更好的想法
  • 这里anotherOne数组的规则是什么?
  • 我想从第一个数组中减去第二个数组。

标签: javascript


【解决方案1】:

你可以试试这个:我正在使用 reducefindIndex 解决这个问题。

var array = [{id :1, name :"test1"},{id :2, name :"test2"},{id :2, name :"test2"},{id :3, name :"test3"},{id :4, name :"test4"}];
var anotherOne = [{id :2, name :"test2"}, {id :4, name :"test4"}];

const res = array.reduce((a, c) => {
    const index = anotherOne.findIndex(item => item.id === c.id);
	
    if (index > -1) {
       /**
        * Remove the matched one from the `anotherOne` array,
        * So that you don't have to match it second time.
        * So it removes the match one once.
        */
        anotherOne.splice(index, 1);
    } else {
        a.push(c);
    }

    return a;
}, []);

console.log(res);
.as-console-wrapper {min-height: 100%!important; top: 0;}

【讨论】:

    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多