Javascript 比较两个数组值的部分

Javascript 比较两个数组值的部分,javascript,Javascript,我有两个阵列: sortKey: ["invoiceDate-desc", "invoiceDate-asc", "location-asc", "location-desc", "orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc", "type-asc", "type-desc", "total-asc", "total-desc"] 及 我想比较以上两个数组,这样结果将包含sortKey中存在的所有值,这些值与re

我有两个阵列:

sortKey: ["invoiceDate-desc", "invoiceDate-asc", "location-asc", "location-desc", "orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc", "type-asc", "type-desc", "total-asc", "total-desc"]

我想比较以上两个数组,这样结果将包含sortKey中存在的所有值,这些值与receivedOrderKey中存在的值部分匹配。例如:由于receivedOrderKey包含invoiceId和orderId,因此结果应该包含来自sortKey的以下值:invoiceId desc、invoiceId asc、orderId asc、orderId-desc。我目前正在使用双For循环解决方案来实现这一点。这样做的有效方式是什么

使用for循环的代码:

          for(i=0;i<sortKey.length;i++){
            var str1 = sortKey[i].toLowerCase();
            for(j=0;j<receivedOrderKey.length;j++){
                var str2 = receivedOrderKey[j].toLowerCase();

                if(str1.includes(str2))
                {
                    requestedOptions.push(sortKey[i]);

                }
            }
        }

requestedOptions: ["orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc"]
使用过滤器

演示

var sortKey=[invoiceDate desc,invoiceDate asc,location asc,location desc,orderId asc,orderId desc,invoiceId asc,invoiceId desc,type asc,type desc,total asc,total desc]; var receivedOrderKey=[invoiceId,orderId,status]; var fnCheck=item=>receivedOrderKey.indexOf item.replace/\-asc | desc/,!=-1. var输出=sortKey.filter s=>fnChecks;
console.log输出;预期的输出是什么?首先编写两个for循环的解决方案。对于这种大小的数组,选择可读的、可维护的代码。除非它每秒运行数千次,否则您不必担心效率。这是另一段代码的一部分,它会在单击搜索时触发ajax。作为要求的一部分,每次都必须这样做。还可以吗?通过网络对服务器的ajax调用将慢几个数量级。编写可读的代码。@Nightshade再次询问,预期的输出是什么?非常感谢!:
          for(i=0;i<sortKey.length;i++){
            var str1 = sortKey[i].toLowerCase();
            for(j=0;j<receivedOrderKey.length;j++){
                var str2 = receivedOrderKey[j].toLowerCase();

                if(str1.includes(str2))
                {
                    requestedOptions.push(sortKey[i]);

                }
            }
        }

requestedOptions: ["orderId-asc", "orderId-desc", "invoiceId-asc", "invoiceId-desc"]
sortKey.filter( s => receivedOrderKey.indexOf( s.replace(/\-(asc|desc)/, "") ) != -1 );