我想将数组的元素与我从mongodb的collection字段中获取的值数组进行比较。除了包含从数据库中获取的值的那些数组,下面的代码对于其他数组也可以正常工作。
此处的代码有效
let array1=["a","b", "c", "d"];
let array2=[ "c", "d", "e", "f", "g"];
var stringArray2= array2.toString();
let finalArray=[];
var pos=0;
for (var i = 1; i <= array1.length; i++) {
const current_appID=array1[i-1].toString();
if(stringArray2.indexOf(current_appID) > -1) {
//console.log(current_appID);
}
else
{
finalArray[pos]=current_appID;
pos++;
}
}
console.log("StringArray2 does not contain b below substr/array elements");
console.log(finalArray);
输出
这里的代码无法正常工作
console.log(db_arr);
//et array1=["a","b", "c", "d"];
//let array2=[ "c", "d", "e", "f", "g"];
//var stringArray2= array2.toString();
const dbArryaString= db_arr.toString(); //db_arr is array fetched from database //297 elements
let finalArray=[];
var pos=0;
for (var i = 1; i <= resulted_ids.length; i++) { // resulted_ids is random array //300 elements
const current_appID=resulted_ids[i-1].toString();
if(dbArryaString.indexOf(current_appID) > -1) {
//console.log(current_appID);
}
else
{
finalArray[pos]=current_appID;
console.log(finalArray[pos]);
pos++;
}
}
console.log("StringArray2 does not contain below substr/array elements");
console.log(finalArray);
输出
所需的输出:(因为db_arr(dbArryaString)不包含result_ids(array)的这些元素)
答案 0 :(得分:0)
在这种情况下,最好避免避免重新发明轮子。
我建议您使用lodash的difference
来执行此操作。这将节省您的麻烦,并使您的代码更整洁。
(所有npm install --save lodash
的拳头)
import {difference} from 'lodash';
let array1 = ["a", "b", "c", "d"];
let array2 = ["c", "d", "e", "f", "g"];
let finalArray = difference(array1, array2)