【问题标题】:Comparing each element of two Arrays - NodeJS比较两个数组的每个元素 - NodeJS
【发布时间】:2021-01-13 06:57:11
【问题描述】:

目标

我想比较两个数组的每个元素,当一个元素在两个数组中都不匹配时,它会被推送到另一个数组。

两个数组的大小都是不确定的。

到目前为止的代码

Example:
//namelist will always have the values present, userlist will check if it has the elements in namelist, otherwise send to another array.

namelist = ['user1','user2','user3','user4','user5']

userlist = ['user4','user1','user3']  //'user2' and 'user5' are not present


//Does not work

let arr1 = [];

let arr2 = [];

for(let i = 0; i < namelist.length && userlist.length; i++){

    if(namelist[i] == userlist[i]){

        arr1  = userlist[i]
    } else {

        arr2  = userlist[i]
    }
}

console.log(arr2);

【问题讨论】:

  • 你想如何处理像["a", "b", "a"]["a", "a", "a"]这样的骗子?给定数组的预期输出是什么?
  • 您是否期望一个数组包含namelist 未在userlist 数组中找到的项目?
  • @ambainBeing,没错。
  • @ggorlen,不会有骗子,因为我是从数据库中提取的,所以不会有骗子。

标签: node.js arrays loops


【解决方案1】:

迭代namelist 并使用Array.includes 检查该数组中的项目是否存在于userlist 中。如果false 添加到result 数组中。

    const namelist = ['user1','user2','user3','user4','user5'];
    const userlist = ['user4','user1','user3'];

    let result = [];
    namelist.forEach(name => {
    if(!userlist.includes(name)){
    result.push(name);
    }
    });
    
    console.info('result::', result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2021-03-21
    • 1970-01-01
    • 2021-05-06
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多