在 Javascript 中创建一个唯一的数组

我在创建包含较大数组的唯一子集的数组时遇到问题,请帮忙!

原阵allMembers (6)[{},{},{},{},{},{}]

allMembers Payload: 0:{id:1, name: Alex} 1:{id:2, name: James} 2:{id:3, name: Bob} 3:{id:4, name: lara} 4:{id:5, name: Dan} 5:{id:6, name: Jes}

第二个数组uniqueMembers (3)[{},{},{}]

 uniqueMembers Payload: 0:{id:1, name: Alex} 1:{id:2, name: James} 2:{id:3, name: Bob}`

我正在寻找的是找到在allMembers但不在的用户uniqueMembers 所以我想要的新数组输出将是以下数组resultArray

resultArray (3)[{},{},{}]

resultArray Payload: 0:{id:4, name: lara} 1:{id:5, name: Dan} 2:{id:6, name: Jes}

我的尝试

 for(let m=0; m<allMembers.length;m++)

        {

            console.log('Testing include statement', uniqueMembers.includes(allMembers[m])) //output always false 

                if(uniqueMembers.includes(allMembers[m]))

                {

                    console.log('ITS ALREADY IN: ', allMembers[m])

                }else{

                    this.setState((prevState) => ({

                        resultArray: [...prevState.resultArray, allMembers[m]] 

                    }));

                    console.log('ITS NOT IN: ', allMembers[m])

                }

        }// resultArray ends up the same as allMembers :( 

任何有关如何获得所需resultArray值的反馈都将不胜感激!


白板的微信
浏览 94回答 3
3回答

潇潇雨雨

如果您的unique数组也非常大,请先将unique数组转换为一组,这样可以节省循环unique数组以检查匹配的时间。然后用于Array.filter获取not in unique元素。let all = [{id:1, name: 'Alex'}, {id:2, name: 'James'},{id:3, name: 'Bob'},{id:4, name: 'lara'},{id:5, name: 'Dan'} ,{id:6, name: 'Jes'}]let unique = [{id:2, name: 'James'},{id:3, name: 'Bob'}]function getNotInUnique(src, target) {&nbsp; let uniqueSet = new Set(target.map(member => member.id))&nbsp; return src.filter(member => !uniqueSet.has(member.id))}console.log(getNotInUnique(all, unique))

慕田峪4524236

构建关联数组以有效查找是否应过滤掉成员。lookup = {}for (const um uniqueMembers)&nbsp; &nbsp;lookup[um.id] = 1;resultArray = allMembers.filter( mem => !lookup.hasOwnProperty(mem) );在此之后发布的两个解决方案建议使用filterand some。这些解决方案是 O(N 2 )。这个应该是 O(N),这样更好。

胡说叔叔

您可以filter与一起使用some。const allMembers = [&nbsp;{id:1, name: 'Alex'},{id:2, name: 'James'},{id:3, name: 'Bob'}, {id:4, name: 'lara'}, {id:5, name: 'Dan'}, {id:6, name: 'Jes'}];const uniqueMembers = [&nbsp;{id:1, name: 'Alex'},{id:2, name: 'James'},{id:3, name: 'Bob'}];const res = allMembers.filter(m => !uniqueMembers.some(({id})=>m.id===id));console.log(res);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript